Data Structures · Bit Manipulation · A Field Guide

Divide two
integers

No multiply, no divide, no modulo. Division is just "how many divisors fit" — and the trick is to count them in powers of two instead of one at a time.

100 ÷ 7 = 14 = 8+4+2
01 · Strip it down

Integer division, but the operators are banned

Compute dividend / divisor truncated toward zero, using only +, −, comparisons, and bit shifts — no *, /, or %. The inputs span the full 32-bit range [−2³¹, 2³¹−1], which is exactly where the sharp edges live. Two subproblems: compute the magnitude fast, and survive the overflow cases.


02 · The governing idea

Count divisor copies in powers of two

Division asks how many times the divisor fits into the dividend. Repeated subtraction answers it one copy at a time — for 2,000,000,000 ÷ 1 that's two billion steps. Instead, subtract exponentially larger chunks: divisor×1, ×2, ×4, ×8…, each built with a left shift (x<<1 = 2x, no multiplication needed).

The key reframe The quotient itself is a binary number. 14 = 8 + 4 + 2 = 1110₂, so 100 ÷ 7 is really asking: which power-of-two chunks of 7 do I need? Each quotient bit answers "do I need 2ⁱ copies of the divisor?"

Paying with big bills first

To pay 43 with denominations 5, 10, 20, 40, you hand over the 40 first, then cover the rest with smaller notes. Always spend the largest chunk that fits.

The sign is a side switch

Don't tangle negatives into the arithmetic. Decide the sign once (XOR of the two signs), work in positive magnitudes, and flip at the very end.

The one value that won't flip

−2³¹ has no positive twin inside int. Cast to long before taking its size, and hard-code the single overflow result.


04 · Watch the bits fill

Scan powers 31 → 0

Set a dividend and divisor. Each step tests one power i: does divisor << i (the current chunk) fit in the remaining dividend? Fits → subtract it and light quotient bit i teal. Too big → skip. The remainder shrinks and the quotient builds up in binary. Sign is handled separately, shown up top.

Bit-scanning divider

remaining dividend (magnitude)
quotient so far

Try 7 ÷ -3 (sign flip → −2), -2147483648 ÷ -1 (the overflow clamp), or 3 ÷ 5 (nothing fits → 0). The bit strip shows only the low powers for readability.


05 · Trace table

Dividing 100 by 7

i chunk = 7 << i remainder Fits? Quotient bit quotient
3 56 100 → 44 yes +8 8
2 28 44 → 16 yes +4 12
1 14 16 → 2 yes +2 14
0 7 2 no — 14

Quotient 8 + 4 + 2 = 14, remainder 2 discarded (truncation toward zero). Powers 31…4 all overshoot 100 and are skipped instantly. The quotient's binary form 1110 falls straight out of which chunks fit.


06 · The code

Thirty-two checks, one overflow guard

int divide(int dividend, int divisor) {
    if (dividend == Integer.MIN_VALUE && divisor == -1)
        return Integer.MAX_VALUE;                 // the one true overflow

    boolean negative = (dividend < 0) ^ (divisor < 0); // sign once, via XOR
    long a = Math.abs((long) dividend);           // cast BEFORE abs
    long b = Math.abs((long) divisor);
    long q = 0;

    for (int i = 31; i >= 0; i--) {
        if ((b << i) <= a) {                        // does this chunk fit?
            a -= (b << i);                          // subtract it
            q += 1L << i;                           // set quotient bit i
        }
    }
    return (int) (negative ? -q : q);
}
Cast, then abs
Math.abs((long) x)
Math.abs(int) on −2³¹ overflows before the widening. Go to long first.
Everything in long
b << i, 1L << i
Shifting a 32-bit magnitude by up to 31 needs 64 bits. Never shift in int.

O(32) time = O(1) for fixed-width ints, O(1) space. Subtraction and shifts are the only arithmetic — all permitted.


07 · Why it's correct

The greedy choice is always safe

The invariant At every step, quotient × divisor + remainder = original dividend (in magnitude). Subtracting a chunk divisor × 2ⁱ and adding 2ⁱ to the quotient preserves the equality exactly. When no chunk fits, the leftover remainder is smaller than the divisor — the truncated answer.

Taking the largest fitting power each time is safe because any remaining amount can still be assembled from smaller powers of two — the same reason every integer has a binary representation. Scanning high-to-low visits each bit once, so no chunk is ever double-counted, and the quotient's binary digits emerge in order.


08 · The 32-bit minefield

Three ways the range bites

−2³¹ ÷ −1

The true answer 2³¹ is one past Integer.MAX_VALUE. It's the only overflow; clamp it explicitly at the top.

abs(−2³¹) in int

Math.abs(Integer.MIN_VALUE) returns itself — still negative. Cast to long before abs so the magnitude fits.

Shifting in int

b << 31 as an int can turn negative or wrap. Do the shift and comparison in long.

Truncation, not floor Because magnitudes are divided and the sign is applied last, −7 ÷ 3 = −2, not −3. The remainder is simply dropped, which truncates toward zero — matching Java's own integer division.

09 · Other traps

Four more ways it slips

Plain repeated subtraction

Correct but O(quotient) — up to ~2 billion steps. Powers-of-two chunking drops it to 32.

Enumerating sign cases

Four if branches for the sign combos is noise. (dividend<0) ^ (divisor<0) is the whole rule.

int quotient accumulator

Accumulate in long, handle the clamp, then cast once at the return. Safer than fighting overflow mid-loop.

Calling it binary search

It's binary decomposition plus greedy subtraction, not search over a sorted array. Related mindset, different mechanism.


10 · The pattern

When unit work is too slow, group it in powers of two

The core move generalizes far beyond division: replace a linear pile of identical operations with an exponential ladder of doublings, then assemble the answer from binary pieces. Subtracting the divisor a billion times becomes subtracting divisor×2ⁱ for 32 values of i.

Fast exponentiation
aⁿ via a², a⁴, a⁸…
multiply the pieces where the exponent's bits are set
Binary lifting
jump 2ⁱ ancestors
reach any depth by combining power-of-two hops

The unifying shape: slow repeated work → group it in powers of two → construct the answer from its binary pieces. Recognizing it turns "arithmetic without operators" from a trick into a derivation.


11 · One month from now

Reconstruct it, don't memorize it

  1. Division = how many divisor copies fit; counting one at a time is too slow.
  2. Count in powers of two instead: build divisor×2ⁱ with left shifts, no multiply.
  3. Scan i from high to low; subtract each chunk that fits and set quotient bit i.
  4. Handle sign separately — XOR the signs, work in positive magnitudes, flip at the end.
  5. Use long (abs of −2³¹ won't fit in int) and clamp the single overflow: −2³¹ ÷ −1 → MAX.
The transferable insight When repeated unit operations are too slow, group them into exponentially growing powers of two and rebuild the answer from its binary pieces. That one idea powers fast exponentiation, binary lifting, doubling techniques, and arithmetic without operators.