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)
{
int n = tokens.size();
if(n == 0)
return 0;
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 c = 0;
if(tokens[i] == "/")
{
if(b != 0)
c = a / b;
}
else if(tokens[i] == "*")
c = a * b;
else if(tokens[i] == "-")
c = a - b;
else
c = a + b;
s.push(c);
}
else
{
int c = atoi(tokens[i].c_str());
s.push(c);
}
}
int a = s.top();
return a;
}
};