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

LeetcodeOJ: Evaluate Reverse Polish Notation Stack

时间:2015-02-18 14:03:44      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

 1 #define ADDITION  ‘+‘
 2 #define SUBSTRACTION  ‘-‘
 3 #define MULTIPLICATION  ‘*‘
 4 #define DIVISION  ‘/‘
 5 
 6 
 7 class Solution {
 8 public:
 9     set<char> tokenSet{+, -, *, /};
10     stack<int> num;
11     int evalRPN(vector<string> &tokens) {
12         for (auto &token : tokens) {
13             auto iter = tokenSet.find( token[token.size()-1] );
14             if ( iter == tokenSet.end() ) {
15                 num.push( atoi( token.c_str() ) );
16             } else {
17                int right = num.top();
18                num.pop();
19                int left = num.top();
20                num.pop();
21                switch ( *iter )
22                {
23                    case ADDITION :
24                        num.push(left + right);
25                        break;
26                    case SUBSTRACTION:
27                        num.push(left - right);
28                        break;
29                    case MULTIPLICATION:
30                        num.push(left * right);
31                        break;
32                    case DIVISION:
33                        num.push(left / right);
34                        break;
35                    default:
36                        break;
37                }
38             }
39         }
40         int ret = num.top();
41         num.pop();
42         return ret;
43     }
44 };

 

LeetcodeOJ: Evaluate Reverse Polish Notation Stack

标签:

原文地址:http://www.cnblogs.com/ydlme/p/4295722.html

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