150. Evaluate Reverse Polish Notation
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计算后缀表达式!用STACK
class Solution {
public:
int evalRPN(vector<string>& tokens)
{
stack<int> shuzi;
for (int i = 0; i < tokens.size(); i++)
{
if(tokens[i] == "+")
{
int a = shuzi.top();
shuzi.pop();
int b = shuzi.top();
shuzi.top() = a + b;
}
else if(tokens[i] == "-")
{
int a = shuzi.top();
shuzi.pop();
int b = shuzi.top();
shuzi.top() = b - a;
}
else if(tokens[i] == "*")
{
int a = shuzi.top();
shuzi.pop();
int b = shuzi.top();
shuzi.top() = a * b;
}
else if(tokens[i] == "/")
{
int a = shuzi.top();
shuzi.pop();
int b = shuzi.top();
shuzi.top() = b / a;
}
else
shuzi.push( atoi(tokens[i].c_str()) );
}
return shuzi.top();
}
};