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) {
int a,b;
stack<int> A;
for(int i=0;i<tokens.size();i++)
{
if(tokens[i]=="*")
{
a=A.top();
A.pop();
b=A.top();
A.pop();
A.push(a*b);
}
else if(tokens[i]=="-")
{
a=A.top();
A.pop();
b=A.top();
A.pop();
A.push(b-a);
}
else if(tokens[i]=="+")
{
a=A.top();
A.pop();
b=A.top();
A.pop();
A.push(a+b);
}
else if(tokens[i]=="/")
{
a=A.top();
A.pop();
b=A.top();
A.pop();
if(a==0)
return -1;
else
A.push(b/a);
}
else
{
A.push(atoi(tokens[i].c_str()));
}
}
return A.top();
}
};
遇到除法一定要检查被除数是否为0!!!!!!!!!!!!!!!!!!!!!!!
依次将vector中的元素压入栈中,如果不是操作符,直接转成int压入栈,如果是操作符,取栈顶两个元素进行运算,并将运算结果重新压入栈中