Yet another iterative Java solution


  • 0
    J
    class Solution {
        public int calculate(String s) {
            char[] chars = s.toCharArray();
            int sum = 0;
            int num = 0;
            boolean op = true; // + true, - false
            Stack<Boolean> needNeg = new Stack<>();
            needNeg.push(false);
            for (int i = 0; i < chars.length; i++) {
                char c = chars[i];
                if (c == ' ') continue;
                if (c == '(') {
                    needNeg.push(!op);
                } else if (c == ')') {
                    needNeg.pop();
                } else if (c == '+' || c == '-') {
                    sum = op ? sum + num : sum - num;
                    op = c == '+' ^ needNeg.peek();
                    num = 0;
                } else {
                    num *= 10;
                    num += c - '0';
                }
            }
            if (num != 0) sum = op ? sum + num : sum - num;
            return sum;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.