Simple Python Solution


  • 0
    G
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        
        prev = 0
        sign = '+'
        res = 0
        i = 0
        
        while i < len(s):
            
            if s[i].isdigit():
                j = i 
                curr = 0
                while j < len(s) and s[j].isdigit():
                    curr = curr * 10 + int(s[j])
                    j += 1
                
                if sign == '+' or sign == '-':
                    prev = curr if sign == '+' else -curr
                elif sign == '*' or sign == '/':
                    if sign == '*':
                        prev = prev * curr 
                    else:
                        if curr == 0:
                            raise ValueError
                        if prev * curr < 0 and prev%curr != 0:
                            prev = prev/curr + 1
                        else:
                            prev = prev/curr
                i = j - 1
                
            elif s[i] in '+-':
                res += prev
                sign = '+' if s[i] == '+' else '-'
                
            elif s[i] in '*/':
                sign = '*' if s[i] == '*' else '/'
                
            i += 1
            
        res += prev
        return res

Log in to reply
 

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