LC 0029 [M] Divide Two Integers - ALawliet/algorithms GitHub Wiki

0b10101 << 1 = 0b101010
0b1000  >> 1 = 0b100
0b10    << 2 = 0b1000
i <<= 1
is
i = i*2
class Solution:
    def divide(self, dividend: int, divisor: int) -> int:
        top = dividend
        bot = divisor

        is_negative = (top > 0 and bot < 0) or (top < 0 and bot > 0)
        top = abs(top)
        bot = abs(bot)
        
        quotient = 0

        while top >= bot:
            cur_bot = bot
            n_divisions = 1
            
            while top >= cur_bot:
                top -= cur_bot
                quotient += n_divisions
                
                cur_bot <<= 1
                n_divisions <<= 1
        
        quotient = -quotient if is_negative else quotient
        return min(max(-2**31, quotient), 2**31 - 1)