Fairly straightforward C++ solution using stack (with code comments)


  • 0
    A
    class Solution {
    public:
        int evalRPN(vector<string>& tokens) {
            stack<int> myStack;
        
            for (int i = 0; i < tokens.size(); i++) {
                string temp = tokens[i];
                if (temp != "-" && temp != "+" && temp != "*" && temp != "/") {
                    myStack.push(atoi(temp.c_str()));  // This must be an integer
                } else {
                    int value1, value2;  // value1 is the number before operand, value2 is after
                    if (!myStack.empty()) {
                        value2 = myStack.top();
                        myStack.pop();
                    } else {
                        return 0;  // operand without any numbers to operate on
                    }
                    
                    if (!myStack.empty()) {
                        value1 = myStack.top();
                        myStack.pop();
                    } else {
                        return 0;  // operand requires 2 numbers, not just one
                    }
                    
                    if (temp == "*") {
                        value1 *= value2;
                    } else if (temp == "-") {
                        value1 -= value2;
                    } else if (temp == "+") {
                        value1 += value2;
                    } else if (temp == "/") {
                        value1 /= value2;
                    } else {
                        return 0;  // unexpected string value
                    }
                    
                    myStack.push(value1);
                }
            }
            
            return myStack.top();
        }
    };
    

Log in to reply
 

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