14 lines simple Python using stack


  • 0

    Here we use a stack to store previous results. One special case we need to keep in mind is a // b != -abs(a // b) when a is negative (b is always non-negative in our problem).

    class Solution(object):
        def calculate(self, s):
            """
            :type s: str
            :rtype: int
            """
            stack = []
            i, sign = 0, "+"
            while i < len(s):
                if s[i].isdigit():
                    tmp = 0
                    while i < len(s) and s[i].isdigit():
                        tmp = tmp * 10 + int(s[i])
                        i += 1
                    stack += [stack.pop()*tmp] if sign == "*"\
                        else [(1,-1)[stack[-1]<0]*(abs(stack.pop())/tmp)] if sign == "/"\
                        else [tmp*(1,-1)[sign == "-"]]
                    continue
                if s[i] in "+-*/":
                    sign = s[i]
                i += 1
            return sum(stack)
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.