美文网首页
227. Basic Calculator II

227. Basic Calculator II

作者: JERORO_ | 来源:发表于2018-07-19 23:29 被阅读0次

问题描述

思路

有运算符,才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))

相关文章

网友评论

      本文标题:227. Basic Calculator II

      本文链接:https://www.haomeiwen.com/subject/hrixmftx.html