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) { int ret=0; int n = tokens.size(); if(n<=0) return ret; stack<int> s; int i=0; while(i<n){ string temp = tokens[i]; int num = atoi(temp.c_str()); //防止非法输入 if(num!=0 || (num==0 && temp[0]=='0')){ s.push(num); }else{ ret = cal(s, tokens[i][0]); if(ret == -1) return 0; } ++i; } if(!s.empty()) return s.top(); else return 0; } int cal(stack<int> &s, char oper){ if(s.size()<2) return -1; int op1 = s.top(); s.pop(); int op2 = s.top(); s.pop(); if(oper == '+'){ s.push(op1+op2); }else if(oper == '-'){ s.push(op2-op1); }else if(oper == '*'){ s.push(op2 * op1); }else if(oper == '/'){ if(op1 == 0) return -1; s.push(op2 / op1); }else return -1; return 0; } };
[LeetCode] Evaluate Reverse Polish Notation,布布扣,bubuko.com
[LeetCode] Evaluate Reverse Polish Notation
原文:http://blog.csdn.net/swagle/article/details/28243489