16ms C++ concise solution


  • 0
    int getStackTop(stack<int>& cal)
        {
            int n = 0;
            if(!cal.empty())
            {
                n = cal.top();
                cal.pop();
            }
            return n;
        }
    
        int evalRPN(vector<string>& tokens) {
            if(tokens.empty()) return 0;
            stack<int> cal;
            for(string token : tokens)
            {
                if(token=="+" || token=="-" || token=="*" || token=="/")
                {
                    int a = getStackTop(cal);
                    int b = getStackTop(cal);
                    if(token=="+") cal.push(a+b);
                    else if(token=="-") cal.push(b-a);
                    else if(token=="*") cal.push(a*b);
                    else if(token=="/") cal.push(a? b/a: 0);
                }
                else
                {
                    cal.push(stoi(token));
                }
            }
            return cal.empty()? 0 : cal.top();
        }
    

Log in to reply
 

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