Divide Two Integers

Pattern: Bits basics

medium

Long division in base 2. From bit 31 down, if divisor × 2^i still fits into what is left of the dividend, subtract it and set bit i of the quotient. Work with absolute values in 64 bits, fix the sign at the end, and clamp the one overflowing case.

The problem

Divide dividend by divisor without using *, / or %, and return the quotient rounded towards zero. Both are 32-bit integers and divisor is not 0. If the true answer is above 2^31 - 1, return 2^31 - 1. For example, 10 / 3 gives 3, 7 / -3 gives -2, and -2147483648 / -1 gives 2147483647.

The function name divide matches LeetCode. Use the link above for the exact statement and limits. The GFG link covers the same idea.

Think first

  • Which single case overflows a 32-bit answer?
  • Subtracting the divisor once per step is too slow for 2^31 / 1. How can you subtract big chunks?
  • How do signs and rounding towards zero work together?

Hints

    Brute force, and why it fails

    Subtract the divisor until the remainder is too small: up to 2^31 steps. Subtracting shifted divisors takes 32 steps.

    The key insight

    Each bit of the quotient can be decided separately, from the biggest down, by asking whether that power-of-two multiple of the divisor still fits.

    Dry run

    a10
    b3
    quotient0

    dividend = 10 and divisor = 3. Both are positive, so a = 10 and b = 3.

    Step 1 of 4

    The plan

    if dividend == -2^31 and divisor == -1: return 2^31 - 1
    negative = exactly one of them is negative
    a = |dividend|, b = |divisor| (64-bit), q = 0
    for i from 31 down to 0:
        if (a >> i) >= b: a = a - (b << i); q = q + 2^i
    return -q if negative else q
    

    Complexity

    Time
    O(1)
    Space
    O(1)

    32 steps, whatever the input.

    Edge cases

    • Dividend 0: 0.
    • Rounding towards zero: -7 / 2 is -3, not -4.
    • Divisor ±1 with the most negative dividend.
    I've built my logic, show the code

    Java

    class Solution {
        public int divide(int dividend, int divisor) {
            if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;   // the only overflow
            boolean negative = (dividend < 0) != (divisor < 0);
            long a = Math.abs((long) dividend), b = Math.abs((long) divisor);
            long quotient = 0;
            for (int shift = 31; shift >= 0; shift--) {     // largest multiples first, like long division in base 2
                if ((a >> shift) >= b) {                    // b * 2^shift fits into what is left
                    a -= b << shift;
                    quotient |= 1L << shift;
                }
            }
            return (int) (negative ? -quotient : quotient);
        }
    }

    C++

    class Solution {
    public:
        int divide(int dividend, int divisor) {
            if (dividend == INT_MIN && divisor == -1) return INT_MAX;   // the only overflow
            bool negative = (dividend < 0) != (divisor < 0);
            long long a = llabs(static_cast<long long>(dividend)), b = llabs(static_cast<long long>(divisor));
            long long quotient = 0;
            for (int shift = 31; shift >= 0; shift--) {     // largest multiples first, like long division in base 2
                if ((a >> shift) >= b) {                    // b * 2^shift fits into what is left
                    a -= b << shift;
                    quotient |= 1LL << shift;
                }
            }
            return static_cast<int>(negative ? -quotient : quotient);
        }
    };

    Python

    class Solution:
        def divide(self, dividend: int, divisor: int) -> int:
            if dividend == -2**31 and divisor == -1:
                return 2**31 - 1                    # the only overflow
            negative = (dividend < 0) != (divisor < 0)
            a, b = abs(dividend), abs(divisor)
            quotient = 0
            for shift in range(31, -1, -1):         # largest multiples first, like long division in base 2
                if (a >> shift) >= b:               # b * 2^shift fits into what is left
                    a -= b << shift
                    quotient |= 1 << shift
            return -quotient if negative else quotient

    Common mistakes

    • Taking Math.abs of -2^31 in 32 bits, which stays negative.
    • Comparing b << i ≤ a, which can overflow; compare a >> i ≥ b instead.
    • Rounding down for negative answers instead of towards zero.

    Similar problems