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
题意
求Reverse Polish Notation.这种表达式的运算值,其实就是求离运算符号最近的两个值(或运算表达式的结果)的运算结果。
题解
这题使用栈来存储要运算的数值就很容易了。只要遇到运算符,就弹出最近的两个数值,再把运算结果入栈即可。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for(auto c:tokens)
{
if(c!="+"&&c!="-"&&c!="*"&&c!="/")
stk.push(stoi(c));
else
{
char key=c[0];
int second=stk.top();
stk.pop();
int first=stk.top();
stk.pop();
if(key=='+')
stk.push(first+second);
else if(key=='-')
stk.push(first-second);
else if(key=='*')
stk.push(first*second);
else if(key=='/')
stk.push(first/second);
}
}
return stk.top();
}
};