227. Basic Calculator II
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers,
+
,
-
,
*
,
/
operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
class Solution {
public:
int calculate(string s) {
long Result = 0;
int n = s.length();
long num = 0;
stack<int> S;
char op = '+';
for(int i = 0;i < n;i ++){
if(s[i] >= '0' && s[i] <= '9'){
num = num * 10 + s[i] - '0';
}
if((s[i] < '0' && s[i] != ' ' )|| i == n - 1){
if(op == '+'){
S.push(num);
}
if(op == '-'){
S.push(-num);
}
if(op == '/'){
int tmp = S.top() / num;
S.pop();
S.push(tmp);
}
if(op == '*'){
int tmp = S.top() * num;
S.pop();
S.push(tmp);
}
op = s[i];
num = 0;
}
}
while(!S.empty()){
Result += S.top();
S.pop();
}
return Result;
}
};