Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/.
Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> myStack;
int first,second,merge;
for(int i=0; i<tokens.size(); i++)
{
if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/")
{
first = myStack.top();
myStack.pop();
second = myStack.top();
myStack.pop();
if(tokens[i] == "+")
merge = first + second;
else if(tokens[i] == "-")
merge = second - first;
else if(tokens[i] == "*")
merge = first * second;
else if(tokens[i] == "/")
merge = second / first;
}
else
{
merge = atoi(tokens[i].c_str());
}
myStack.push(merge);
}
return myStack.top();
}
};
05-07 15:17