c++ stack-based solution


  • 0
    H
    class Solution {
    public:
        int calculate(string s) {
            stack<int> stk;
            int num;
            char op = '+';
            istringstream iss(s);
            while(iss >> num) {
                if(op == '+') stk.push(num);
                else if(op == '-') stk.push(-num);
                else {
                    int last = stk.top();
                    stk.pop();
                    if(op == '*') last *= num;
                    else last /= num;
                    stk.push(last);
                }
                iss >> op;
            }
            int ans = 0;
            while(!stk.empty()) {
                ans += stk.top();
                stk.pop();
            }
            return ans;
        }
    };
    

Log in to reply
 

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