首页 > 代码库 > Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation
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在微软面试考到了,此处没有考虑溢出的问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。