227. Basic Calculator II

class Solution {
    public int calculate(String s) {
        char sign = '+';
        Stack<Integer> stack = new Stack<>();
        int num = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                num = num*10 + (s.charAt(i) - '0');

            }
            // i == s.length()-1 -> after have number, immideiatly cal it!!
            if (!Character.isDigit(c) && c != ' ' || i == s.length()-1) {
                if (sign == '+') {
                    stack.push(num);
                } else if (sign == '-') {
                    stack.push(-num);
                } else if (sign == '*') {
                    int prev = stack.pop();
                    stack.push(prev * num);
                } else if (sign == '/') {
                    int prev = stack.pop();
                    stack.push(prev / num);
                }
                sign = c;
                num = 0;
            }
        }
        
        int result = 0;
        while (!stack.isEmpty()) {
            result += stack.pop();
        }
        return result;
    }
}
/**
if + or - just put into stack

* or / pop from stack to cal with current val
3/2 = 1 

  
4
3

at last pop all number in stack to add together


3+3+
 */

Last updated