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

【Leetcode】Evaluate Reverse Polish Notation

时间:2014-10-01 13:35:41      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   sp   div   

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

栈的典型应用

 1 class Solution {
 2 public:
 3     int evalRPN(vector<string> &tokens) {
 4         int ans = 0;
 5         stack<int> s;
 6         for(int i = 0; i < tokens.size(); ++i) {
 7             if (tokens[i] == "+") {
 8                 int b = s.top();
 9                 s.pop();
10                 int a = s.top();
11                 s.pop();
12                 a += b;
13                 s.push(a);
14             } else if (tokens[i] == "-") {
15                 int b = s.top();
16                 s.pop();
17                 int a = s.top();
18                 s.pop();
19                 a -= b;
20                 s.push(a);
21             } else if (tokens[i] == "*") {
22                 int b = s.top();
23                 s.pop();
24                 int a = s.top();
25                 s.pop();
26                 a *= b;
27                 s.push(a);
28             } else if (tokens[i] == "/") {
29                 int b = s.top();
30                 s.pop();
31                 int a = s.top();
32                 s.pop();
33                 a /= b;
34                 s.push(a);
35             } else {
36                 s.push(atoi(tokens[i].c_str()));
37             }
38         }
39         return s.top();
40     }
41 };

 

【Leetcode】Evaluate Reverse Polish Notation

标签:style   blog   http   color   io   ar   for   sp   div   

原文地址:http://www.cnblogs.com/dengeven/p/4003174.html

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