Think of the problem as two-levels


  • 0
    B

    There are two levels in an expression, the low level(+, -) and high level(*, /).
    The two levels will be computed separately: once you get into the high level, you save the last low level operator(+ or -); once you get out of the high level, you get this high level result, compute with the last low level operator, added this value into the final result.

    public int calculate(String s) {
        if(s == null || s.isEmpty())
            return 0;
        
        char lastOp = '+', lastLowOp = '+';
        boolean lowLevel = true;
        int result = 0, resultH = 0, num = 0;
        
        s = s + "+"; // handle last operator
        for(char c: s.toCharArray()){
            if(c == ' ') continue;
            if(c >= '0' && c <= '9'){
                num = num * 10 + c - '0';
                continue;
            }
            if(c == '*' || c == '/'){
                if(lowLevel){ // get into high level
                    lastLowOp = lastOp;
                    resultH = num;
                    lowLevel = false;
                }else
                    resultH = compute(lastOp, resultH, num);
            }else{ // c == '+' || c == '-' 
                if(!lowLevel){  // get out of high level
                    resultH = compute(lastOp, resultH, num);
                    result = compute(lastLowOp, result, resultH);
                    lowLevel = true;
                }else
                    result = compute(lastOp, result, num);
            }
            lastOp = c;
            num = 0;
        }
        return result;
    }
    
    private int compute(char operator, int result, int num) {
        switch(operator){
        case '+': return result + num;
        case '-': return result - num;
        case '*': return result * num;
        case '/': return result / num;
        default:
            return -1;
        }
    }

Log in to reply
 

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