描述
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
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
分析:
用栈存储数字(stoi转字符串为数字),遇到操作符,出栈两次,再把结果入栈,最后输出栈中的唯一元素。
注意数字可能为负数的情况。
代码:
int evalRPN(vector<string> &tokens) {
stack<int> s;
int x,y,z,n;
for (vector<string>::iterator it=tokens.begin();it!=tokens.end();it++ )
{
switch((*it)[0])
{
case '+':
y=s.top();
s.pop();
x=s.top();
s.pop();
z=x+y;
s.push(z);
break;
case '-':
if ((*it)[1]=='\0')
{
y=s.top();
s.pop();
x=s.top();
s.pop();
z=x-y;
s.push(z);
}
else
{
n=stoi(*it);
s.push(n);
}
break;
case '*':
y=s.top();
s.pop();
x=s.top();
s.pop();
z=x*y;
s.push(z);
break;
case '/':
y=s.top();
s.pop();
x=s.top();
s.pop();
z=x/y;
s.push(z);
break;
default:
n=stoi(*it);
s.push(n);
}
}
return s.top();
}