C++ clean solution


  • 0
    • Array nums stores all additive items from the expression, i.e., all '*' and '/' items are pre-calculated.
        int calculate(string s) {
            s += '+';
            char sign = '+';
            vector<int> nums;
            
            for (int i = 0, cur = 0; i < s.size(); ++i) {
                if (isdigit(s[i])) cur = getNum(s, i);
                else if (s[i] != ' ') {
                    switch (sign) {
                        case '+': break;
                        case '-': cur *= -1; break;
                        case '*': cur *= nums.back(), nums.pop_back(); break;
                        case '/': cur = nums.back()/cur, nums.pop_back(); break;
                    }
                    nums.push_back(cur), cur = 0, sign = s[i];
                }
            }
            
            return accumulate(nums.begin(), nums.end(), 0);
        }
        
        int getNum(string& s, int& i) { // get numeric value starting at i
            auto j = s.find_first_not_of("0123456789", i);   
            auto res = stoi(s.substr(i, j-i));
            return i = j-1, res;
        }
    

Log in to reply
 

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