29. Divide Two Integers leetcode python new season 2016

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.


class Solution(object):
    MAX_INT = 0x7FFFFFFF
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        if dividend == 0:
            return 0
        if divisor == 0:
            return self.MAX_INT
        negative = (dividend > 0) ^ (divisor > 0)
        dividend, divisor = abs(dividend), abs(divisor)
        result = 0
        while dividend >= divisor:
            divisor_sum = divisor
            count = 1
            while divisor_sum << 1 <= dividend:
                divisor_sum <<= 1
                count <<= 1
            dividend -= divisor_sum
            result += count
        result = self.MAX_INT if not negative and result > self.MAX_INT else result
        return -result if negative else result
            


你可能感兴趣的:(29. Divide Two Integers leetcode python new season 2016)