Leetcode 150

根据逆波兰表示法,求表达式的值。

有效的运算符包括 +-*/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

  • 整数除法只保留整数部分。
  • 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

分析:实际上逆波兰表示就是后缀表示,特别需要注意一下就是除法的计算,由于版本不一样python的除法还是会有一些区别,用下面的方法个人觉得比较安全可靠

class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        result = 0
        temp = []
        for item in tokens:
            if item not in ['+', '-', '*', '/']:
                temp.append(int(item))
            else:
                num2 = temp.pop()
                num1 = temp.pop()
                result = self.calculate(num1, num2, item)
                temp.append(result)
        return temp.pop()
                
    def calculate(self,num1, num2, operation):
        if operation == '+':
            return num1 + num2
        if operation == '-':
            return num1 - num2
        if operation == '*':
            return num1 * num2
        if operation == '/':
            return int( num1 / (num2 * 1.0)) 

猜你喜欢

转载自blog.csdn.net/jhlovetll/article/details/84288828