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
题意:逆波兰应用,很明显要考察的是栈;要注意的是,就是新来的符号,将栈中两个值取出进行操作。再放回栈中。
此时先取出的num2,后取出的是num1;进行num1和num2的操作;
[cpp] view plain copy
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
if (tokens.empty())
{
return 0;
}
stack<int> st;
for (int i=0; i<tokens.size(); i++)
{
string s = tokens[i];
if (s =="+" || s=="-"
|| s=="*" || s=="/")
{
if (st.size()<2)
{
return 0;
}
int num2 = st.top();
st.pop();
int num1 = st.top();
st.pop();
int result = 0;
if (s=="+")
{
result = num1 + num2;
}
if (s == "-")
{
result = num1 - num2;
}
if (s == "*")
{
result = num1 * num2;
}
if (s == "/")
{
result = num1 / num2;
}
st.push(result);
}
else
{
st.push(atoi(s.c_str()));
}
}
return st.top();
}
};