Leetcode Oj reverse polish notation

来源:互联网 发布:夜访吸血鬼影评 知乎 编辑:程序博客网 时间:2024/06/04 20:16

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

Solution using Python

Pay special attention to division in python 2.7

class Solution:    # @param tokens, a list of string    # @return an integer    def evalRPN(self, tokens):        stack = []        for i in range(0,len(tokens)):            if tokens[i]=="+":                a = stack.pop()                b = stack.pop()                c= int(a)+int(b)                stack.append(str(c))            elif tokens[i]=="-":                a = stack.pop()                b = stack.pop()                c= int(b)-int(a)                stack.append(str(c))            elif tokens[i]=="*":                a = stack.pop()                b = stack.pop()                c= int(a)*int(b)                stack.append(str(c))            elif tokens[i]=="/":                a = stack.pop()                b = stack.pop()                if int(a) * int (b) <0 and abs(int(b)) %abs(int(a)) !=0:                    c= int(b)/int(a) +1                else:                    c= int(b)/int(a)                 stack.append(str(c))                            else:                 stack.append(tokens[i])        return int(stack.pop())


0 0
原创粉丝点击