基本计算器

基本计算器

224. 基本计算器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int calculate(string s) {
//思路:由于只有+、-操作,将括号展开,借助于栈
stack<int> sign; //栈顶记录当前符号
sign.push(1); //默认为 +

int res = 0;
int num = 0;
int op = 1;

for(char ch : s){ //遍历 空格自动跳过
if(ch>='0' && ch<='9'){ //遇到数值
num = num*10 + (ch-'0');
continue;
}
res += op * num; //计算一个运算符
num = 0; //数值清空

if(ch=='+') op = sign.top();
else if(ch=='-') op = -sign.top();
else if(ch=='(') sign.push(op); //进入左括号,把左括号之前的符号置于栈顶
else if(ch==')') sign.pop(); //退出括号,弹出栈顶符号
}

res += op*num; //计算最后一个数

return res;
}
};
-------------本文结束 感谢阅读-------------
0%