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
s=tokens.size();
stack<
int
> s1;
for
(auto token : tokens)
{
if
(token !=
"+"
&& token !=
"-"
&& token !=
"*"
&& token !=
"/"
)
{
stringstream ss;
ss<<token;
int
temp;
ss>>temp;
s1.push(temp);
}
else
{
int
a,b;
a=s1.top(); s1.pop(); b=s1.top(); s1.pop();
if
(token==
"+"
)
s1.push(a+b);
else
if
(token==
"*"
)
s1.push(a*b);
else
if
(token==
"-"
)
s1.push(b-a);
else
s1.push(b/a);
}
}
return
s1.top();
}
};