C++ 12ms clean solution, using stack


  • 0
    class Solution {
    public:
    int evalRPN(vector<string>& tokens) {
        stack<int> nums;
        int a;
        for (auto &s:tokens){
            if (s=="+"){
                a=nums.top();nums.pop();
                nums.top()+=a;
            }else if (s=="-"){
                a=nums.top();nums.pop();
                nums.top()-=a;
            }else if (s=="/"){
                a=nums.top();nums.pop();
                nums.top()/=a;
            }else if (s=="*"){
                a=nums.top();nums.pop();
                nums.top()*=a;
            }else{
                nums.push(stoi(s));
            }
        }
        return nums.top();
    }
    };

Log in to reply
 

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