[LeetCode]Evaluate Reverse Polish Notation

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        stack<int> numStack;
        //for each token in the tokens
        for(int i = 0; i < tokens.size(); ++i)
        {
            //if the token is operator
            if(tokens[i] == "+" || tokens[i] == "-"
            || tokens[i] == "*" || tokens[i] == "/")
            {
                //push out two number in the numStack, compute result under current operator
                int val2 = numStack.top();//...suppose valid notation
                numStack.pop();
                int val1 = numStack.top();//...suppose valid notation
                numStack.pop();
                int newNum = opFuns(val1, val2, tokens[i]);//...
                numStack.push(newNum);
            }
            //if the token is number
            else
            {
                numStack.push(stoi(tokens[i]));
            }
        }
        //return the result
        return numStack.top();
    }
    int opFuns(int a, int b, string op)
    {
        if(op == "+")
            return a+b;
        else if(op == "-")
            return a-b;
        else if(op == "*")
            return a*b;
        else
            return a/b;
    }
};

你可能感兴趣的:([LeetCode]Evaluate Reverse Polish Notation)