题目描述
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:
翻译(Google):在反向波兰表示法中计算算术表达式的值。
有效运算符位于 - ,*,/。 每个操作数可以是整数或另一个表达式。
一些例子:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
//用一个栈,如果遇到+,-,*,/符号,则将最上面两个数字弹出栈,计算值,再压入栈
//如果不是符号,则把字符串转化为数字,压入栈,注意,因为栈是后进先出,所以
//计算(2,1,-)的值时,弹出来的先是1,再是2,所以这里要注意用先弹出来的数字作
//为减数,后弹出来的数字作为被减数,同样在/的时候,用先弹出的数字作为除数,
//用后弹出来的数字作为被除数。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> s;
if(tokens.size()==0)return 0;
for(int i=0;i<tokens.size();++i)
{
if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/")
{
int a,b;
a=s.top();
s.pop();
b=s.top();
s.pop();
if(tokens[i]=="+")s.push(a+b);
else if(tokens[i]=="-")s.push(b-a);
else if(tokens[i]=="*")s.push(a*b);
else s.push(b/a);
}
else
{
s.push(atoi(tokens[i].c_str()));
}
}
return s.top();
}
};