LRU Cache @ LeetCode (Python)
Valid Palindrome @ LeetCode (Python)

Evaluate Reverse Polish Notation @ LeetCode (Python)

kitt posted @ 2014年3月01日 19:27 in LeetCode , 3076 阅读

Python 6/-132结果为-1, 系统认为结果为0, 所以对除法使用了int(op1 * 1.0 / op2)。

class Solution:
    # @param tokens, a list of string
    # @return an integer
    def evalRPN(self, tokens):
        stack = []
        for i in tokens:
            if i not in ('+', '-', '*', '/'):
                stack.append(int(i))
            else:
                op2 = stack.pop()
                op1 = stack.pop()
                if i == '+': stack.append(op1 + op2)
                elif i == '-': stack.append(op1 - op2)
                elif i == '*': stack.append(op1 * op2)
                else: stack.append(int(op1 * 1.0 / op2))
        return stack[0]

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter