class Solution {
public:
int calculate(string s) {
stack<int> stk;
int res = 0, cur = 0, n = s.size();
char c = '+';//记录上一次的符号
for(int i = 0; i <= n; ++i){//这儿<=n,是为了保证最后一个数字得到处理
if(isdigit(s[i])) cur = 10*cur + (s[i] - '0');
else if(isspace(s[i])) continue;
else{
if(c == '+') stk.push(cur);//当前累计的数字
else if(c == '-') stk.push(-cur);//转化为负数
else if(c == '*'){
cur *= stk.top(); stk.pop();
stk.push(cur);
}
else if(c == '/'){
cur = stk.top()/cur; stk.pop();
stk.push(cur);
}
cur = 0;
c = s[i];//更新上一次的符号
}
}
while(!stk.empty()){//全部相加
res += stk.top();
stk.pop();
}
return res;
}
};
或者更好理解的:
class Solution {
public:
int calculate(string s) {
char op = '+';
istringstream ss(s);
stack<int> stk;
int val, res = 0;
while(ss>>val){//自动忽略空格
if(op == '+') stk.push(val);
else if(op == '-') stk.push(-val);
else if(op == '*'){
int v = stk.top(); stk.pop();
stk.push(v*val);
}else{
int v = stk.top(); stk.pop();
stk.push(v/val);
}
ss >> op;//更新操作符
}
while(!stk.empty()){
res += stk.top(); stk.pop();
}
return res;
}
};