227. Basic Calculator II

2018-07-19  本文已影响0人  JERORO_

问题描述

思路

有运算符,才append到stack中
是数字的话,等待进位
如果不在s末尾加入+0,会导致最后一个运算符后的数字丢失

    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s or len(s) == 0:
            return 0
        s=s+"+0"

        num = 0
        opt = "+"
        stack = []
        for i in s:

            if i.isdigit():
                num = num*10 + int(i)
            elif not i.isdigit() and not i.isspace():
                if opt == "+":
                    stack.append(num)
                elif opt == "-":
                    stack.append(-num)
                elif opt == "*":
                    stack.append(stack.pop()*num)
                elif opt == "/":
                    n =stack.pop()
                    if n<0:
                        tmp = abs(n)//num
                        stack.append(-tmp)
                    else:
                        stack.append(n//num)
                opt = i
                num = 0

        return int(sum(stack))
上一篇 下一篇

猜你喜欢

热点阅读