9ms c++ solution


  • 0
    X
    int evalRPN(vector<string>& tokens) {
            stack<int> st;
            int result = 0;
            for(string str: tokens){
                //first + - * /, then numbers
                if (str.compare("-") == 0){
                    int a = st.top();
                    st.pop();
                    int b = st.top();
                    st.pop();
                    st.push(b - a);
                }
                
                else if (str.compare("+") == 0){
                    int a = st.top();
                    st.pop();
                    int b = st.top();
                    st.pop();
                    st.push(b + a);
                }
                
                else if (str.compare("*") == 0){
                    int a = st.top();
                    st.pop();
                    int b = st.top();
                    st.pop();
                    st.push(b * a);
                }
                
                else if (str.compare("/") == 0){
                    int a = st.top();
                    st.pop();
                    int b = st.top();
                    st.pop();
                    st.push(b / a);
                }
                
                //then it should be numbers!
                else {
                    int a = stoi(str);
                    st.push(a);
                }
            }
            
            if (!st.empty()) result = st.top();
            
            return result;
        }
    

Log in to reply
 

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