题目:https://leetcode-cn.com/problems/basic-calculator-ii/
实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。
class Solution {
public:
int calculate(string s) {
char c = '+';
int n = s.length();
long long tmp = 0;
stack<long long> st;
for(int i = 0;i < n;i++) {
if(s[i] == ' ') continue;
if('0'<=s[i]&&s[i]<='9') {
tmp = 0;
while(i<n&&'0'<=s[i]&&s[i]<='9')
tmp = tmp*10+s[i]-'0',i++;
i--;
if(c=='*') st.top() *= tmp;
else if(c=='/') st.top() /= tmp;
else if(c=='-') st.push(-1*tmp);
else st.push(tmp);
}
else c = s[i];
}
long long res = 0;
while(!st.empty()) res += st.top(),st.pop();
return res;
}
};