Problem
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
Solution
1. 一开始居然没有想到借助 stack.............



2.
Bug 数字没有考虑它有可能是负数,自带正负号。。。。
另外一个技巧,借助 token[0] 用 switch 语句提高点效率。。。
class Solution {
int convert( const string& token){
int sign = 1;
const char *p = &token[0];
if(token[0] == '-') sign = -1;
if(token[0] == '+' || token[0] =='-') p = &token[1];
return sign*atoi(p);
}
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for( auto token : tokens){
if(isdigit(token[0]) || token.size() > 1){
stk.push(convert(token));
}
else {
int num2 = stk.top();
stk.pop();
int num1 = stk.top();
stk.pop();
int rst = 0;
switch(token[0]){
case '+' :
rst = num1 + num2;
break;
case '-' :
rst = num1 - num2;
break;
case '*' :
rst = num1 * num2;
break;
case '/' :
rst = num1 / num2;
break;
}
stk.push(rst);
}
}
return stk.top();
}
};