C++ clean solution with stack


  • 0
    • sign: sign of current item
    • signs: stack of signs in front of each opening '('
        int calculate(string s) {
            int res = 0, sign = 1;
            stack<int> signs; signs.push(1);
            
            for (int i = 0; i < s.size(); ++i)
                switch (s[i]) 
                {
                    case ' ': break;
                    case '(': signs.push(signs.top()*sign), sign = 1; break;
                    case ')': signs.pop(); break;
                    case '+': sign = 1; break;
                    case '-': sign = -1; break;
                    default: // digit
                        int num = s[i] - '0';
                        while (i+1 < s.size() && isdigit(s[i+1]))
                            num = 10*num + (s[++i] - '0');
                        res += sign*signs.top()*num;
                }
            
            return res;
        }
    

Log in to reply
 

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