美文网首页
1.3 调车场问题

1.3 调车场问题

作者: 做一只有趣的芦苇 | 来源:发表于2020-11-13 15:49 被阅读0次

    面试题 16.26. 计算器

    def calculate(self, s: str) -> int:
            stack,base = [],'0123456789'
            i,n = 0,len(s)
            while i < n:
                if s[i] == " ": 
                    i += 1
                    continue
                c = s[i] # 保存操作符
                if c in '+-*/': #找到数字的位置
                    i += 1  
                    while i < n and s[i] == " ":
                        i += 1
                num = 0
                while i < n and s[i] in base: #如果是连续数字,需要更新栈顶数据
                    num = num * 10 + int(s[i])
                    i += 1
                if c == '-':  # 根据之前保存的操作符对应计算
                    num = -num
                elif c == '*':
                    num = stack.pop()*num
                elif c == '/':
                    tmp = stack.pop()
                    num = int(operator.truediv(tmp, num)) # 等同于下面代码 改变python原有除法取整
                    # if (tmp > 0 and num < 0):
                    #     num = -(tmp // (-num))
                    # elif (tmp < 0 and num > 0):
                    #     num = -((-tmp) // num)
                    # elif (tmp<0 and num<0):
                    #     num = (-tmp) // (-num)
                    # else:
                    #     num = tmp//num
                stack.append(num)
            return sum(stack)
    

    相关文章

      网友评论

          本文标题:1.3 调车场问题

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