22ms Java solution without stack


  • 0
    C

    Inspired by @czonzhu 's post for the "Expression Add Operators" problem at https://discuss.leetcode.com/topic/24523/java-standard-backtrace-ac-solutoin-short-and-clear

    public int calculate(String s) {
            if(s == null || s.length() == 0)
                return 0;
            int result = 0, prev = 0, i = 0;
            char sign = '+';
            while(i < s.length()) {
                char c = s.charAt(i);
                if(Character.isDigit(c)) {
                    int n = c - '0';
                    while(i+1 < s.length() && Character.isDigit(s.charAt(i+1))) {
                        n = n*10 + s.charAt(i+1) - '0';
                        i++;
                    }
                    switch(sign) {
                        case '+' : result += n; prev = n; break;
                        case '-' : result -= n; prev = -n; break;
                        case '*' : result = result - prev + prev*n; prev = prev*n; break;
                        case '/' : result = result - prev + prev/n; prev = prev/n;
                            break;
                    }
                }else if("+-*/".indexOf(c) != -1) {
                    sign = c;
                }
                i++;
            }
            return result;
        }
    

Log in to reply
 

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