Post my solution in C, 4ms.


  • 0
    X

    The idea behind this is simple. Main function handles only + and -, when there is a * or /, it calls helper.
    sum records the partial results and cur holds the current operand.

       void skip(char **s) {
            while(**s ==' ') (*s)++;
        }
        int getN(char **s) {
            skip(s);
            int ret = 0;
            while((**s >= '0') &&(**s <='9')){
                ret = ret *10 + (**s -'0');
                (*s)++;
            }
            return ret;
        }
        // Node getOp returns operation but s is still pointing to the
        // operation after the call.
        char getOp(char **s) {
            skip(s);
            char ret = **s;
            return ret;
        }
        // This function only handles * and /
        int cal(int a, char **s){
            int b;
            char op = getOp(s);
            while(op == '*' || op =='/') {
                (*s)++;
                b = getN(s);
                if(op=='*') a = a*b;
                else a = a/b;
                op =getOp(s);
            }
            return a;
        } 
        // This function only handles + and -.
        int calculate(char* s) {
            if(s == NULL || *s == 0 ) return 0;
            int sum = 0;
            int cur = getN(&s);
            char op;
            while(*s) {
                op = getOp(&s);
                if( op == '+' || op == '-') {
                    sum += cur;
                    s++;
                    cur = getN(&s);
                    if(op == '-') {
                        cur = -cur;
                    }
                } else if ( op == '*' || op == '/') {
                    cur = cal(cur, &s);
                }
            }
            sum += cur;
            return sum;
        }

Log in to reply
 

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