Title: https://leetcode-cn.com/problems/basic-calculator-ii/
implement a basic calculator to calculate the value of a simple string expression
The string expression contains only non-negative integers, +,-, *, / four operators and spaces. Integer division preserves only the integer part.
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;
}
};