Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

150. Evaluate Reverse Polish Notation 🌟🌟

You are given an array of strings tokens that represents an arithmetic expression in a Reverse Polish Notation.

Evaluate the expression. Return an integer that represents the value of the expression.

Note that:

Stack Solution

Code

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<long long> st;
        for(auto x: tokens){
            if(x=="+"|| x=="-" || x=="*" || x=="/"){
                int b = st.top();st.pop();
                int a = st.top();st.pop();

                if(x=="+"){
                    st.push(a+b);
                }else if(x=="-"){
                    st.push(a-b);
                }else if(x=="*"){
                    st.push((long)a*(long)b);
                }else if(x=="/"){
                    st.push(a/b);
                }
            }else{
                st.push(stoi(x));
            }
        }
        return st.top();
    }
};