Basic Calculator II. I pass the same test case, but when i submit, i get a wrong


  • 0
    S
    class Solution {
    public:
    int calculate(string s) {
        int x = 0;
        int y = 0;
        char op1 = '+';
        char op2 = '+';
        
        for(int i = 0; s[i]; ++ i) {
            int val = 0;
            while(s[i] && s[i] == ' ') { ++ i; }
            while(s[i] && isdigit(s[i])) {
                val = val * 10 + s[i] - '0';
                ++ i;
            }
            
            switch(op2) {
                case '+' :
                case '-' :
                    switch(op1) {
                        case '+' :
                            x += y;
                            break;
                        case '-' :
                            x -= y;
                            break;
                    }
                    y = val;
                    op1 = op2;
                    break;
                case '*' :
                    y *= val;
                    break;
                case '/' :
                    y /= val;
                    break;
            }
          
            while(s[i] && s[i] == ' ') { ++ i; }
            op2 = s[i];
        }
        
        if(op1 == '+') { x += y; }
        else { x -= y; }
        
        return x;
    }
    

    };

    The test case is :

    "123456789*10"


Log in to reply
 

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