美文网首页
29. Divide Two Integers

29. Divide Two Integers

作者: April63 | 来源:发表于2018-06-20 21:57 被阅读0次

    总的来说是减法没错,但是一个一个减去时间一定会超,所以做法是减去1倍,2倍, 4倍,没办法减以后再从1倍开始。

    class Solution(object):
        def divide(self, dividend, divisor):
            """
            :type dividend: int
            :type divisor: int
            :rtype: int
            """
            positive = (dividend < 0) is (divisor < 0)
            dividend, divisor = abs(dividend), abs(divisor)
            res = 0
            while dividend >= divisor:
                temp, i = divisor, 1
                while dividend >= temp:
                    dividend -= temp
                    res += i
                    i = i << 1
                    temp = temp << 1
            if not positive:
                res = -res
            return min(max(-pow(2,31), res),pow(2,31)-1)
    

    相关文章

      网友评论

          本文标题:29. Divide Two Integers

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