题目描述
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) {
if(tokens.size()<=0) return -1;
stack<int>res;
std::reverse(tokens.begin(),tokens.end());
while(!tokens.empty())
{
string front=tokens.back();
tokens.pop_back();
if(!getoper(front)||res.empty()) res.push(atoi(front.c_str()));
else{
int num1=res.top();
res.pop();
int num2=res.top();
res.pop();
switch(front[0])
{
case '+':res.push(num2+num1);break;
case '-':res.push(num2-num1);break;
case '*':res.push(num2*num1);break;
case '/':res.push(num2/num1);break;
default:;
}
}
}
return res.top();
}
private:
bool getoper(string obj)
{
return obj=="+"||obj=="-"
||obj=="*"||obj=="/";
}
};
灵活运用字符串到数字,数字到字符的转换。