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

LeetCode – Refresh – Evaluate Reverse Polish Notation

时间:2015-03-19 09:59:59      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

Just use a stack to record the numbers. And evey time you encounter a operator, pop two numbers, calucate it and push it back.

Do not disorder the numbers. Otherwise you will get wrong answer when the operators are "-" and "/".

 

More harder part is how you get these incoming vector of strings from keyboard input, when it has parethesis involved.

 1 class Solution {
 2 public:
 3     int getValue(int num1, int num2, string op) {
 4         if (op == "+") {
 5             return num1 + num2;
 6         } else if (op == "-") {
 7             return num1 - num2;
 8         } else if (op == "*") {
 9             return num1 * num2;
10         }
11         return num1 / num2;
12     }
13     int evalRPN(vector<string> &tokens) {
14         int len = tokens.size();
15         if (len == 0) return 0;
16         stack<int> s;
17         for (int i = 0; i < len; i++) {
18             if (tokens[i] == "+" ||
19                 tokens[i] == "-" || 
20                 tokens[i] == "/" || 
21                 tokens[i] == "*") {
22                 int num2 = s.top();
23                 s.pop();
24                 int num1 = s.top();
25                 s.pop();
26                 s.push(getValue(num1, num2, tokens[i]));
27             } else {
28                 s.push(stoi(tokens[i]));
29             }
30         }
31         return s.top();
32     }
33 };

 

LeetCode – Refresh – Evaluate Reverse Polish Notation

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4349431.html

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