Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

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

0 votes
63 views

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();
    }

};
asked Dec 17, 2013 in Evaluate Reverse Polish Notation by xhx (160 points)
edited Dec 18, 2013 by xhx

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

1 Answer

+1 vote
 
Best answer

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

answered Dec 17, 2013 by Shangrila (14,150 points)
selected Dec 17, 2013 by xhx

thank you very much. The code has been accepted.


...