Sometime got Compile Error, Sometime say Runtime Error //Last executed input: ["18"]


  • 0
    X

    I have updated the code witch now works.
    The method to solve this problem is:
    when meet a number, push it into the stack.
    when meet a operator(+, -, *, /), pop two number from the stack, do the math and push the result into the stack again. that's how to Evaluate Reverse Polish Notation.

    #include <stack>
    
    class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
             
            stack<int> st;
            int a, b;
            for (int i = 0; i < tokens.size(); i++){
                if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/"){
                    st.push(atoi(tokens[i].c_str()));
                    continue;
                }
    
                b = st.top();st.pop();
                a = st.top();st.pop();
                switch(tokens[i][0]){
                case '+':
                    st.push(a+b);break;
                case '-':
                    st.push(a-b);break;
                case '*':
                    st.push(a*b);break;
                case '/':
                    st.push(a/b);break;
                }
            }
            return st.top();
        }
        
    };

  • 2
    S

    You should initialize the i in for (int i; i < tokens.size(); i++)


  • 0
    S

    Could you please update the post with explanation of algorithm and comments in code?


  • 0
    X

    thank you very much. The code has been accepted.


Log in to reply
 

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