My solution, calculate * and / first


  • 0
    M
    int calculate(string s) {
        int num = 0, rst = 0;
        int lastNum = 0;
        int markOp = 1, lastOp = 1; //1:+, -1:-, 2:*, 3:/
        
        s += "+";
        for(auto ch:s) {
            if(ch >= '0' && ch <= '9') {
                num = num*10+ch-'0';
            }
            else if(ch == ' ') {
                continue;
            }
            else {
                if(lastOp < 2) lastNum = num;
                else if(lastOp == 2) lastNum *= num;
                else lastNum /= num;
                num = 0;
                
                if(ch == '+' || ch == '-') {
                    rst += markOp * lastNum;
                    markOp = (ch == '+') ? 1 : -1;
                    lastOp = markOp;
                    lastNum = 0;
                }
                else {
                    lastOp = (ch == '*') ? 2 : 3;
                }
            }
        }
        
        return rst;
    }

Log in to reply
 

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