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.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
Note: Do not use the eval built-in library function.
整体思路是:先处理乘除,遇到加减先压栈
public int calculate2(String s) {
if(s==null){
throw new IllegalArgumentException();
}
int d=0;//记录压栈的值
int res=0; //记录最后的结果
Character sign='+'; //记录的是前一个符号,也就是数字前的符号
Stack<Integer> nums=new Stack<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)>='0'){
d=d*10+s.charAt(i)-'0';
}
if(s.charAt(i)<'0' && s.charAt(i)!=' '|| i==s.length()-1){
if(sign=='+') nums.push(d);
if(sign=='-') nums.push(-d);
if(sign=='*' || sign=='/'){
int temp=sign=='*'?nums.pop()*d:nums.pop()/d;
nums.push(temp);
}
//压栈后重新记录符号和数字
sign=s.charAt(i);
d=0;
}
}
//处理加减
while (!nums.empty()){
res+=nums.pop();
}
System.out.print(res);
return res;
}