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> data;
for(int i=0; i<tokens.size(); i++)
{
if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/")
{
int second = data.top();
data.pop();
int first = data.top();
data.pop();
if(tokens[i]=="+")
data.push(first+second);
else if(tokens[i]=="-")
data.push(first-second);
else if(tokens[i]=="*")
data.push(first*second);
else
data.push(first/second);
}
else
data.push(string_to_int(tokens[i]));
}
return data.top();
}
int string_to_int(string s)
{
int res=0;
int i=0;
if(s[0] == '-')
i=1;
for(;i<s.length(); i++)
res = res*10 + s[i]-48;
if(s[0] == '-')
res = -res;
return res;
}
};