- 算式计算
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>store;
for(auto x:tokens)
{
if(x=="+"||x=="-"||x=="*"||x=="/")
//遇到符号就对符号进行出栈,然后计算,结果再入栈
{
if(store.size()<2)
return 0;
int a=store.top();store.pop();
int b=store.top();store.pop();
int c=0;
if(x=="+")
c=b+a;
else if(x=="-")
c=b-a;
else if(x=="*")
c=b*a;
else if(x=="/")
c=b/a;
store.push(c);
}
else
store.push(atoi(x.c_str()));
}
return store.top();
}
};