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:
Input: " 3+5 / 2 " Output: 5
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function.
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
char sign = '+';//为第一个数准备的符号
int base = 0;
//自始至终我们都是从左到右按顺序计算的
for(int i = 0;i<s.length();i++){
char c = s.charAt(i);
if(c>='0'&&c<='9'){//数字
base = base*10 + c-'0';
}
if( (!Character.isDigit(c)&&c!=' ') || i==s.length()-1 ){//遇到运算符 或者 到了最后一位
if(sign=='+'){// prev number + int(c)
stack.push(base);
}
else if(sign=='-'){// prev number - int(c) = prev number + (-int(c))
stack.push(-base);
}
else if(sign=='*'){// prev number * int(c) 直接运算出结果放入stack(四则运算中乘除法优先级最高)
stack.push( stack.pop()*base );
}
else if(sign=='/'){// prev number / int(c) 直接运算出结果放入stack(四则运算中乘除法优先级最高)
stack.push( stack.pop()/base );
}
base = 0;//base已经放入stack,该清零为下一次遇到数字做准备了
sign = c;//为接下来遇到的数字安排的符号
}
}
//此时只剩下加法了
int res= 0;
for(int n:stack){
res += n;
}
return res;
}
}