问题:”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> num;
int length = tokens.size();
for(int i=0;i<length;i++)
{
if(tokens[i].compare("+")==0)
num.push(getSum(num,1));
else if(tokens[i].compare("-")==0)
num.push(getSum(num,2));
else if(tokens[i].compare("*")==0)
num.push(getSum(num,3));
else if(tokens[i].compare("/")==0)
num.push(getSum(num,4));
else
num.push(stoi(tokens[i]));
}
return num.top();
}
int getSum(stack<int>& num,int symbol)
{
int num1,num2;
num1 = num.top();num.pop();
num2 = num.top();num.pop();
switch(symbol)
{
case(1):return num1+num2;break;
case(2):return num2-num1;break;
case(3):return num1*num2;break;
case(4):{
if(num1==0)
return 0;
else
return num2/num1;
break;
}
default:return 0;
}
return 0;
}
};