[Clean C++] Standard solution with stack


  • 0
    H
    class Solution {
    public:
        int evalRPN(vector<string>& tokens) {
            stack<int> nums;
            for (string it : tokens) {
                if (it == "+" || it == "-" || it == "*" || it == "/") {
                    int n2 = nums.top();
                    nums.pop();
                    int n1 = nums.top();
                    nums.pop();
    
                    switch (it[0]) {
                        case '+' : { nums.push(n1 + n2); break; }
                        case '-' : { nums.push(n1 - n2); break; }
                        case '*' : { nums.push(n1 * n2); break; }
                        case '/' : { nums.push(n1 / n2); break; }
                    }
                } else {
                    nums.push(atoi(it.c_str()));
                }
            }
            return nums.top();
        }
    };
    

Log in to reply
 

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