leetcode之Evaluate Reverse Polish Notation

这道题是很基础的数据结构知识。唯一需要注意的是6/(-32)网站给的结果是0,python给的是-1,我也不知道为什么。。。代码如下:

class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        if tokens == []:
            return 0
        if tokens == ['']:
            return 0
        listofnum = []
        symbol = ['+', '-', '*', '/']
        for i in tokens:
            if i in symbol:
                a = listofnum.pop()
                b = listofnum.pop()
                if i == '+':
                    listofnum.append(int(a) + int(b))
                if i == '-':
                    listofnum.append(int(b) - int(a))
                if i == '*':
                    listofnum.append(int(a) * int(b))
                if i == '/':
                    if int(b) < 0:
                        if int(a) > 0:
                            listofnum.append(-(-int(b) / int(a)))
                        else:
                            listofnum.append(int(b) / int(a))
                    else:
                        if int(a) < 0:
                            listofnum.append(-(int(b) / (-int(a))))
                        else:
                            listofnum.append(int(b) / int(a))
            else:
                listofnum.append(int(i))
            # print listofnum
        return int(listofnum[0])


阅读更多
上一篇leetcode之Basic Calculator
下一篇leetcode之Range Sum Query - Mutable
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭