public int calculate(String s) {
if (s == null || s.isEmpty()) {
return 0;
}
int n = s.length();
int num = 0;
int res = 0;
char op = '+';
Stack<Integer> nStack = new Stack<>();
int sign = 1;
for (int i = 0; i < n; i++) {
char cur = s.charAt(i);
if (Character.isDigit(cur)) {
num = num * 10 + Character.getNumericValue(cur);
} else if (cur == '+' || cur == '-') {
res = calc(res, op, num);
op = cur;
num = 0;
} else if (cur == '*' || cur == '/') {
if (op == '*' || op == '/') {
res = calc(res, op, num);
} else if (op == '+' || op == '-') {
nStack.push(res);
sign = op == '+' ? 1 : -1;
res = num * sign;
}
op = cur;
num = 0;
}
}
res = calc(res, op, num);
while (!nStack.isEmpty()) {
num = nStack.pop();
res = calc(num, '+', res);
}
return res;
}
private int calc(int n1, char op, int n2) {
switch (op) {
case '+':
return n1 + n2;
case '-':
return n1 - n2;
case '*':
return n1 * n2;
case '/':
return n1 / n2;
}
return 0;
}