class Solution {
public int calculate(String s) {
Stack<Character> operators = new Stack();
Stack<Integer> nums = new Stack();
int i = 0;
while (i < s.length()) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
int num = c - '0';
while ((i + 1) < s.length() && Character.isDigit(s.charAt(i + 1))) {
num = 10 * num + s.charAt(i + 1) - '0';
++i;
}
nums.push(num);
}
else if (isOperator(c)) {
while (!operators.isEmpty() && hasPrecedence(c, operators.peek())) {
nums.push(calculate(operators.pop(), nums.pop(), nums.pop()));
}
operators.push(c);
}
++i;
}
while (!operators.isEmpty()) {
nums.push(calculate(operators.pop(), nums.pop(), nums.pop()));
}
return nums.isEmpty() ? 0 : nums.pop();
}
public boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
public int calculate(char operator, int num1, int num2) {
int res = 0;
switch(operator) {
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num2 * num1;
break;
case '/':
res = num2 / num1;
break;
}
return res;
}
public boolean hasPrecedence(char op1, char op2) {
if ((op2 == '-' || op2 == '+') && (op1 == '*' || op1 == '/')) {
return false;
}
return true;
}
}