面试题42:计算逆波兰表达式(RPN)

  这是一个比较简单的题目,借助栈可以轻松实现逆波兰表达式。

题目描述:

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         stack<int> s;
 5         for(string str : tokens){
 6             if(str == "+" || str == "-" || str == "*" || str == "/"){
 7                 int a = s.top();s.pop();
 8                 int b = s.top();s.pop();
 9                 if(str == "+"){
10                     s.push(b+a);
11                 }else if(str == "-"){
12                     s.push(b - a);
13                 }else if(str == "*"){
14                     s.push(b*a);
15                 }else{
16                     s.push(b/a);
17                 }
18             }else{
19                 s.push(std::stoi(str));
20             }
21         }
22         return s.top();
23     }
24 };

 

posted @ 2017-06-06 10:12  wxquare  阅读(746)  评论(0编辑  收藏  举报