当前位置:网站首页>leetcode-224:基本计算器
leetcode-224:基本计算器
2022-07-02 23:55:00 【菊头蝙蝠】
题目
题目连接
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
注意:不允许使用任何将字符串作为数学表达式计算的内置函数,比如 eval() 。
示例 1:
输入:s = "1 + 1"
输出:2
示例 2:
输入:s = " 2-1 + 2 "
输出:3
示例 3:
输入:s = "(1+(4+5+2)-3)+(6+8)"
输出:23
解题
方法一:栈
class Solution {
public:
int calculate(string s) {
int res=0,num=0,sign=1;
stack<int> st;
for(char c:s){
if(c>='0'&&c<='9'){
num=num*10+(c-'0');
}
else if(c=='+'||c=='-'){
res+=sign*num;
num=0;
sign=c=='+'?1:-1;
}
else if(c=='('){
st.push(res);
st.push(sign);
res=0;
sign=1;
}
else if(c==')'){
res+=sign*num;
num=0;
res*=st.top();
st.pop();
res+=st.top();
st.pop();
}
}
res+=sign*num;
return res;
}
};
边栏推荐
- Problèmes de configuration lex & yacc & Bison & Flex
- 【AutoSAR 六 描述文件】
- [MCU project training] eight way answering machine
- [Luogu p4320] road meets (round square tree)
- 【案例分享】让新时代教育发展与“数”俱进
- 关于XML一些介绍和注意事项
- Win10 多种方式解决无法安装.Net3.5的问题
- Redis21 classic interview questions, extreme pull interviewer
- 【AutoSAR 三 RTE概述】
- 线程的启动与优先级
猜你喜欢
随机推荐
2022上半年值得被看见的10条文案,每一句都能带给你力量!
百度智能云牵头打造智能云综合标准化平台
cordova-plugin-device获取设备信息插件导致华为审核不通过
1.12 - 指令
How SQLSEVER removes data with duplicate IDS
Rust ownership (very important)
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
【AutoSAR 十二 模式管理】
File operation io-part2
MySQL 23 classic interview hanging interviewer
1.11 - 总线
Program analysis and Optimization - 9 appendix XLA buffer assignment
Briefly talk about other uses of operation and maintenance monitoring
【JetCache】JetCache的配置说明和注解属性说明
【AutoSAR 十三 NVM】
程序分析与优化 - 9 附录 XLA的缓冲区指派
百数不断创新,打造自由的低代码办公工具
Vulkan-性能及精细化
Two common methods and steps of character device registration
Markdown tutorial









