【LeetCode练习题】Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation

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
 
题目意思:
计算出波兰计数法的结果。


解题思路:
利用一个栈,遇到数字就压栈,遇到符号就弹出两个数字,计算结果再push到栈里去。
注意几个函数就行了:isdigit()、stoi()。

代码如下:
 1 class Solution {
 2 public:
 3     int evalRPN(vector<string> &tokens) {
 4         stack<int> ret;
 5         int len = tokens.size();
 6         for(int i = 0; i < len; i++){
 7             if( isdigit(tokens[i][0]) || tokens[i].size() > 1){
 8                 //如果是负数,第一个就是符号。
 9                 ret.push(stoi(tokens[i]));
10             }
11             else{
12                 int op2 = ret.top();
13                 ret.pop();
14                 int op1 = ret.top();
15                 ret.pop();
16                 
17                 //注意除法和减法顺序,是用后pop出来的减去先pop出来的
18                 switch(tokens[i][0]){
19                     case '+':
20                         ret.push(op1 + op2);
21                         break;
22                     case '-':
23                         ret.push(op1 - op2);
24                         break;
25                     case '*':
26                         ret.push(op1 * op2);
27                         break;
28                     case '/':
29                         ret.push(op1 / op2);
30                         break;
31                 }
32             }
33         }
34         return ret.top();
35     }
36 };

 



posted on 2014-04-05 17:47  Allen Blue  阅读(177)  评论(0编辑  收藏  举报

导航