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+22" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5
思路:
關鍵在于怎么處理乘法和除法,如果是乘法或者除法,我們需要用前面的數和當前的數做運算。因此此處可以用棧來記錄前面的數字,用一個符號變量記錄前一個符號,當遍歷到一個新數字時,判斷一下前面的符號是什么,如果是乘除,就和前面的數字運算,如果是+,就向棧中push這個數字,如果是-,就push這個數字的負數。
遍歷到結尾,把最后一個數字入棧,此時棧中存放的都是要進行加法運算的數字。
public int calculate(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int num = 0, res = 0;
char op = '+';
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + c - '0';
}
if (i == s.length() - 1 || (!Character.isDigit(c) && c != ' ')) {
if (op == '+') {
stack.push(num);
} else if (op == '-') {
stack.push(-num);
} else if (op == '*') {
stack.push(stack.pop() * num);
} else if (op == '/') {
stack.push(stack.pop() / num);
}
op = c;
num = 0;
}
}
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}