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
逆波兰式,通过栈解决,进栈出栈把握好(数据进,遇到符号弹出俩个)
//记得判断些不应该的情况
int evalRPN(vector<string> &tokens) {
stack<int> data_stack;
int num_left,num_right,result;
string str;
for(int i = 0;i < tokens.size();i++ )
{
str = tokens.at(i);
if(!isdigit(str[0])&&str.size()==1)//运算符的一种
{
if(data_stack.size()<2)return 0;
num_right = data_stack.top();
data_stack.pop();//没有返回值!
num_left = data_stack.top();//最后弹出
data_stack.pop();
switch(str[0])
{
case '+' : result = num_left + num_right;break;
case '-' : result = num_left - num_right;break;
case '*' : result = num_left * num_right;break;
case '/' : result = num_left / num_right;break;
default : return 0;//非其中一种,则报错
}
data_stack.push(result);
}
else
{
data_stack.push(stoi(str,NULL));//stoi(str,NULL)此处是string类型,平常使用的atoi 参数为char *类型
}
}
return data_stack.top();
}