首页 > 其他 > 详细

[LeetCode] Evaluate Reverse Polish Notation

时间:2015-04-15 11:26:35      阅读:211      评论:0      收藏:0      [点我收藏+]

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

解题思路:

后缀表达式计算的问题,做过计算机的同学应该都知道。遇到数字,进栈;遇到操作符,将前面两个操作数出栈,计算,将结果入栈。最后的结果会在栈中。

代码如下:

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> s;
        int len = tokens.size();
        int num1, num2;
        for(int i = 0; i<len; i++){
            if(tokens[i]=="+"){
                num1 = s.top();
                s.pop();
                num2 = s.top();
                s.pop();
                num1 = num2 + num1;
                s.push(num1);
            }else if(tokens[i] == "-"){
                num1 = s.top();
                s.pop();
                num2 = s.top();
                s.pop();
                num1 = num2 - num1;
                s.push(num1);
            }else if(tokens[i] == "*"){
                num1 = s.top();
                s.pop();
                num2 = s.top();
                s.pop();
                num1 = num2 * num1;
                s.push(num1);
            }else if(tokens[i] == "/"){
                num1 = s.top();
                s.pop();
                num2 = s.top();
                s.pop();
                num1 = num2 / num1;
                s.push(num1);
            }else{
                s.push(stringToInt(tokens[i]));
            }
        }
        return s.top();
    }
    
    int stringToInt(const string& s){
        int len = s.length();
        int result = 0;
        int sign = 1;
        int i = 0;
        if(s[0]=='-'){
            sign = -1;
            i=1;
        }
        while(i<len){
            result = s[i] - '0' + result * 10;
            i++;
        }
        return sign * result;
    }
};


[LeetCode] Evaluate Reverse Polish Notation

原文:http://blog.csdn.net/kangrydotnet/article/details/45055155

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!