首页 > 其他 > 详细

LeetCode – Refresh – Evaluate Reverse Polish Notation

时间:2015-03-19 09:58:01      阅读:276      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!