https://leetcode.com/problems/basic-calculator-ii
public class Solution { public int calculate(String s) { Stack<Integer> stack = new Stack<>(); char sign = '+'; int num = 0; int result = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { num = num * 10 + s.charAt(i) - '0'; } if (!(s.charAt(i) >= '0' && s.charAt(i) <= '9') && s.charAt(i) != ' ' || i == s.length() - 1) { if (sign == '+') { stack.push(num); } else if (sign == '-') { stack.push(-1 * num); } else if (sign == '*') { stack.push(stack.pop() * num); } else if (sign == '/') { stack.push(stack.pop() / num); } num = 0; sign = s.charAt(i); } } while (!stack.isEmpty()) { result += stack.pop(); } return result; } }