美文网首页
29. Divide Two Integers 按位做循环减法,

29. Divide Two Integers 按位做循环减法,

作者: 羲牧 | 来源:发表于2020-05-31 18:46 被阅读0次

    运用一般的循环减法,会超时。
    运用按位左移的方法,实在是妙!值得细细体会

    class Solution:
        
        def divide(self, dividend: int, divisor: int) -> int:
            if divisor == 0 or dividend == 0:
                return 0
            if (dividend < 0 and divisor < 0) or (dividend > 0 and divisor > 0):
                flag = True
            else:
                flag = False
            
            if dividend == -2147483648 and divisor == -1:
                return 2147483647
            if divisor == 1:
                return dividend
            
            dividend = abs(dividend)
            divisor = abs(divisor)
            count = 0
            for i in reversed(range(31)):
                cur = divisor << i
                if dividend >= cur:
                    count |= 1 << i
                    dividend = dividend - cur
                    # print(i, dividend, divisor)
            if not flag:
                count = 0 - count
            return count
          
    

    相关文章

      网友评论

          本文标题:29. Divide Two Integers 按位做循环减法,

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