C++ solution, 30ms


  • 0
    X
    class Solution {
    private:
    	int compute(int a, int b, string oper)
    	{
    		int res = 0;
    		if("+" == oper)
    			res = a + b;
    		else if("-" == oper)
    			res = a - b;
    		else if("*" == oper)
    			res = a * b;
    		else res = a / b;
    		return res;
    	}
    
    public:
        int evalRPN(vector<string> &tokens) {
    		stack<int> s;
    		for(int i = 0; i < tokens.size(); ++i)
    		{
    			if("+" == tokens[i] || "-" == tokens[i] || "*" == tokens[i] || "/" == tokens[i])
    			{
    				int b = s.top();
    				s.pop();
    				int a = s.top();
    				s.pop();
    				int temp = compute(a, b, tokens[i]);
    				s.push(temp);
    			}
    			else
    			{
    				istringstream iss(tokens[i]);
    				int temp;
    				iss >> temp;
    				s.push(temp);
    			}
    		}
    		return s.top();
        }
    };

Log in to reply
 

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