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

LeetCode150 Evaluate Reverse Polish Notation

时间:2016-12-08 23:14:42      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:blog   value   code   val   dia   ati   span   ken   opera   

Evaluate the value of an arithmetic expression in Reverse Polish Notation.  (Medium)

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 evalRPN(vector<string>& tokens) {
 4         stack<int> s;
 5         for (int i = 0;i < tokens.size();i++) {
 6             if (tokens[i] == "+" || tokens[i] == "-" || tokens[i]== "*" || tokens[i] == "/") {
 7                 int num1 = s.top();
 8                 s.pop();
 9                 int num2 = s.top();
10                 s.pop();
11                 if (tokens[i] == "+") {
12                     int num = num1 + num2;
13                     s.push(num);
14                 }
15                 if (tokens[i] == "-") {
16                     int num = num2 - num1;
17                     s.push(num);
18                 }
19                 if (tokens[i] == "*") {
20                     int num = num2 * num1;
21                     s.push(num);
22                 }
23                 if (tokens[i] == "/") {
24                     int num = num2 / num1;
25                     s.push(num);
26                 }
27             }
28             else {
29                 s.push(atoi(tokens[i].c_str()));
30             }
31         }
32         int ans = s.top();
33         return ans;
34     }
35 };

 

LeetCode150 Evaluate Reverse Polish Notation

标签:blog   value   code   val   dia   ati   span   ken   opera   

原文地址:http://www.cnblogs.com/wangxiaobao/p/6146708.html

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