227 Basic Calculator II
227. Basic Calculator II
1. Question
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 52. Implementation
class Solution {
public int calculate(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int num = 0, res = 0;
char sign = '+';
Stack<Integer> stack = new Stack<>();
int len = s.length();
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = 10 * num + c - '0';
}
//字符是运算符或者到达字符串结束处,需要计算最后一次结果
if (isOperator(c) || i == len - 1) {
if (sign == '+') {
stack.push(num);
}
else if (sign == '-') {
stack.push(-num);
}
else if (sign == '*') {
stack.push(stack.pop() * num);
}
else if (sign == '/') {
stack.push(stack.pop() / num);
}
sign = c;
num = 0;
}
}
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}
public boolean isOperator(char c ) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
}3. Time & Space Complexity
4. Follow Up
Last updated