標籤:
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
解題思路:
注意:測試中會出現“4*3/5”這樣的情況,因此,可以用一個TempRes儲存上一次運算的結果,TempOp表示距離本次運算子最近的+-運算子,具體看代碼即可:
static public int calculate(String s) {int res = 0, tempRes = 0, Option = 1, tempOp = 1;for (int i = 0; i < s.length(); i++) {switch (s.charAt(i)) {case ‘ ‘:break;case ‘+‘:Option = 1;break;case ‘-‘:Option = -1;break;case ‘*‘:Option = 2;break;case ‘/‘:Option = 3;break;default:int num = 0;while (i < s.length() && Character.isDigit(s.charAt(i)))num = num * 10 + s.charAt(i++) - ‘0‘;i--;switch (Option) {case 1:res += tempOp * tempRes;tempRes = num;tempOp = 1;break;case -1:res += tempOp * tempRes;tempRes = num;tempOp = -1;break;case 2:tempRes *= num;break;case 3:tempRes /= num;}}}res += tempOp * tempRes;return res;}
Java for LeetCode 227 Basic Calculator II