20 ms ,short JAVA , with annotation


  • 2

    For example : 5+6 * 7-9
    ,can be read as : (+5)+ (+6)*(7)+ (-9)
    so we can use '+'add each part result(+5),(+6)*(7), (-9)to the main result untill we encounter '+' or '-'

            int res = 0;
            int cur;
            char op = '+';        //the first number is postive
            int curRes = 0;       // part result
    
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                // 5+*6*7-9=       
                if (Character.isDigit(c)) {
                    cur = c - '0';
                    while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) {
                        cur = cur * 10 + s.charAt(++i) - '0';
                    }
                    switch (op) {
                        case '+':         // the num's former op is '+' 
                            curRes += cur; break;
                        case '-':         
                            curRes -= cur;break;
                        case '*':         
                            curRes *= cur;break;
                        case '/':         
                            curRes /= cur;break;
                    }
                } else {
                    if (c == '+' || c == '-') {
                        res = res + curRes;             // put the part result to the main result
                        curRes = 0;
                        op = c;                               // next part result will need this op
                    } else if (c == '*' || c == '/') {
                        op = c;
                    }
                }  // end else
            }    //end for
            return res + curRes;                     // no op '+' or '-'  behind the finall part ,so we + curRes
    

Log in to reply
 

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