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
1 class Solution { 2 public: 3 int matoi(string &s){ 4 if(s.length()<1) 5 cerr<<"Invalid Input"<<endl; 6 int rst = 0; 7 bool isPositive = true; 8 int i = 0; 9 if(s[0]=='+'){ 10 ++i; 11 }else if(s[0]=='-'){ 12 isPositive =false; 13 ++i; 14 } 15 16 for(; i < s.length(); ++i){ 17 if(s[i]<'0'||s[i]>'9') 18 cerr<<"Invalid Input"<<endl; 19 rst = rst*10 + s[i]-'0'; 20 } 21 if(!isPositive) 22 rst = -rst; 23 return rst; 24 } 25 int evalRPN(vector<string> &tokens) { 26 stack<int> istack; 27 set<string> oper; 28 oper.insert("+"); 29 oper.insert("-"); 30 oper.insert("/"); 31 oper.insert("*"); 32 33 for(int i = 0 ; i < tokens.size();++i){ 34 if(oper.count(tokens[i])){ //oper 35 if(istack.size()<2) 36 cerr<<"Invalid Input"<<endl; 37 int operand1 = istack.top(); 38 istack.pop(); 39 int operand2 = istack.top(); 40 istack.pop(); 41 if(tokens[i]=="+") 42 istack.push(operand1+operand2); 43 else if(tokens[i]=="-") 44 istack.push(operand2-operand1); 45 else if(tokens[i]=="*") 46 istack.push(operand1*operand2); 47 else if(tokens[i]=="/") 48 istack.push(operand2/operand1); 49 else 50 cerr<<"Invalid Input"<<endl; 51 }else 52 istack.push(matoi(tokens[i])); 53 } 54 return istack.top(); 55 } 56 };
手一贱又刷了一道。。。。真的睡觉了
atoi在微软面试考到了,此处没有考虑溢出的问题
转载于:https://www.cnblogs.com/nnoth/p/3744758.html