码迷,mamicode.com
首页 > 其他好文 > 详细

Evaluate Reverse Polish Notation

时间:2014-05-22 15:28:54      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   c   code   java   

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

bubuko.com,布布扣
 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 };
bubuko.com,布布扣

手一贱又刷了一道。。。。真的睡觉了

atoi在微软面试考到了,此处没有考虑溢出的问题

Evaluate Reverse Polish Notation,布布扣,bubuko.com

Evaluate Reverse Polish Notation

标签:style   blog   class   c   code   java   

原文地址:http://www.cnblogs.com/nnoth/p/3744758.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!