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
Solution: stack.
1 class Solution { 2 public: 3 int evalRPN(vector<string> &tokens) { 4 stack<int> s; 5 for (int i = 0; i < tokens.size(); ++i) { 6 if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/") 7 s.push(stoi(tokens[i])); 8 else { 9 int op2 = s.top();s.pop(); 10 int op1 = s.top();s.pop(); 11 int result = 0; 12 if(tokens[i] == "+") 13 result = op1 + op2; 14 else if(tokens[i] == "-") 15 result = op1 - op2; 16 else if(tokens[i] == "*") 17 result = op1 * op2; 18 else if(tokens[i] == "/") 19 result = op1 / op2; 20 s.push(result); 21 } 22 } 23 return s.top(); 24 } 25 };