leetcode 227. Basic Calculator II

来源:互联网 发布:萌拍相机软件 编辑:程序博客网 时间:2024/06/08 05:10
class Solution(object):    def calculate(self, s):        """        :type s: str        :rtype: int        """        stack,operand,operator = [0],0,'+'        for i in range(len(s)):            if s[i].isdigit():                operand = operand*10+ord(s[i])-ord('0')            if not s[i].isdigit() and not s[i].isspace() or i == len(s)-1:                if operator == '+':                    stack.append(operand)                elif operator == '-':                    stack.append(-operand)                elif operator == '*':                    stack.append(stack.pop() * operand)                else:                    tmp = stack.pop()                    if tmp < 0:                        stack.append(-1*(-tmp//operand))                    else:                        stack.append(tmp//operand)                operand = 0                operator = s[i]        return sum(stack)

原创粉丝点击