Divide Two Integers

Key Idea

Then repeat:

19 / 3 3 1 6 2 12 4 24 8 too large 19 - 12 = 7 quotient += 4

Then repeat:

7 / 3 3 1 6 2 12 4 too large 7 - 6 = 1 quotient += 2

Final:

quotient = 8 + 4 + 2 = 14

So:

43 / 3 = 14




## Solution

```python
class Solution:
    def divide(self, dividend: int, divisor: int) -> int:
        INT_MIN = -2**31
        INT_MAX = 2**31 - 1

        # Overflow case: LeetCode expects clamp
        if dividend == INT_MIN and divisor == -1:
            return INT_MAX

        negative_output = (dividend < 0) != (divisor < 0)

        dividend = abs(dividend)
        divisor = abs(divisor)

        quotient = 0

        while dividend >= divisor:
            current_divisor = divisor
            current_quotient = 1

            # Keep doubling while it still fits
            while dividend >= (current_divisor << 1):
                current_divisor <<= 1
                current_quotient <<= 1

            dividend -= current_divisor
            quotient += current_quotient

        return -quotient if negative_output else quotient

Complexity

Where n = abs(dividend).