Evaluate the value of an arithmetic expression in Reverse Polish Notation.
+
, -
, *
, /
. 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
Subscribe to see which companies asked this question
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for (string str : tokens){
if (!isOp(str)){
stk.push(stoi(str));
}
else{
int num1 = stk.top(); stk.pop();
int num2 = stk.top(); stk.pop();
int num=0;
switch (str[0])
{
case '+':num = num1 + num2; break;
case '-':num = num2 - num1; break;
case '*':num = num1*num2; break;
case '/':num = num2 / num1; break;
default:
break;
}
stk.push(num);
}
}
return stk.top();
}
private:
bool isOp(string str){
if (str.size()==1&&(str[0] == '+' || str[0] == '-' ||
str[0] == '*' || str[0] == '/')){
return true;
}
return false;
}
};