Divide Two Integers

Divide one int by another using only shifts, additions and subtractions, rounding toward zero.

Given two integers dividend and divisor, return dividend divided by divisor without using multiplication, division or the mod operator. The divisor is never 0. The result drops its fraction, rounding toward zero, so 8.345 becomes 8 and -2.73 becomes -2.

Assume you can only store 32-bit signed integers, so values run from -231 to 231 - 1. If the true result is above 231 - 1, return 231 - 1.

Example 1
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10 / 3 = 3.333..., rounded toward zero to 3.
Example 2
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7 / -3 = -2.333..., rounded toward zero to -2.
Solution

The Idea

Say you have 10 biscuits and pack them in bags of 3. How many full bags do you get? You fill a bag and take 3 away: 10, then 7, then 4, then 1. One biscuit is too few for another bag, so the answer is 3 bags, which is exactly 10 / 3 in Example 1.

That works with nothing but subtraction, and it is a fine way for 10 biscuits. Now try 2,147,483,647 divided by 1. Taking away 1 at a time means more than two billion subtractions. So the question is: can each step take away a much bigger piece, and still tell us how many divisors that piece holds?

It can, because a Java int is kept as a row of 32 binary digits, each 0 or 1 and called a bit, and moving every one of them one place to the left doubles the number. The divisor 3 is 0011 in its last four bits. The operator << does the move, so 3 << 1 is 0110, which is 6, and 3 << 2 is 1100, which is 12. No multiplication is used.

Look at the picture below. The left side lists the copies of the divisor 3, shifted left by 0, 1 and 2 places, with the bit positions numbered from 0 on the right. The right side shows the rounds of the division.

Dividing 10 by 3. The divisor 3 is 0011 in binary; shifted left one place it is 0110, which is 6, and two places 1100, which is 12, more than 10. Round 1 takes 6 from 10, leaving 4, and the quotient gets 2. Round 2 takes 3 from 4, leaving 1, and the quotient gets 1. The quotient is 0011, which is 3.

In round 1, what is left is 10. The copy 12, marked "too big", does not fit, so the biggest copy that fits is 6, the divisor shifted 1 place. Taking 6 away leaves 4, and since 6 holds two 3s, the answer so far, called the quotient, gets 2.

In round 2, what is left is 4. Now 6 is too big, so the copy is 3 itself, shifted 0 places. Taking it away leaves 1, and the quotient gets 1 more. In the box "1 is less than 3: stop", nothing more fits, and the quotient is 2 + 1 = 3.

Look at the quotient at the bottom of the picture, 0011. Round 1 shifted the divisor 1 place and set bit 1 of the quotient. Round 2 shifted it 0 places and set bit 0. Each round fills in one bit of the answer, which is long division as taught at school, done with the digits 0 and 1.

Solution Approach

Five questions stand between those rounds and working code: why bigger pieces beat single subtractions, how to handle the signs, why to work with negative numbers, how to shift within 32 bits, and the one answer too big for an int.

Taking away bigger pieces

How much faster is a round than one subtraction? Subtracting the divisor once per step takes as many steps as the answer, up to about two billion. A round instead finds the biggest shifted copy that fits, which sets the highest bit the quotient still needs.

Each later round sets a lower bit, so the number of rounds is at most the number of 1 bits in the quotient. A positive int uses only the lower 31 of its 32 bits, so 31 rounds is the most that can happen.

Handling the signs

What about Example 2, 7 / -3? The sizes give 7 / 3 = 2, and the sign is settled separately. The result is negative when exactly one of the two inputs is negative, so 7 / -3 is -2 and -7 / -3 is 2. Dropping the fraction of the sizes is the same as rounding toward zero.

Working with negative numbers

So why not make both inputs positive? The reason is how Java stores negative int values, in a system called two's complement. The top bit of the 32 bits counts as -231, and -3 is stored as 11111111111111111111111111111101.

This gives one more negative value than positive ones. The smallest, -2,147,483,648 or Integer.MIN_VALUE, has no positive partner, and Math.abs(Integer.MIN_VALUE) returns -2,147,483,648 again. Every positive value does have a negative partner, so the code turns both inputs negative instead.

With negative numbers the comparisons flip. "What is left still holds the divisor" means 10 ≥ 3 for the sizes, and -10 ≤ -3 for the negatives. Shifting still doubles: -3 << 1 is -6, and -6 << 1 is -12. Using long would also avoid the problem, but the statement allows only 32-bit integers.

Shifting without going past 32 bits

Can a shift itself go wrong? If the copy of the divisor is already below half of Integer.MIN_VALUE, doubling it would drop past -231 and wrap around to a positive value. Shifting right by one place with >> halves a number, so half of the minimum is Integer.MIN_VALUE >> 1, which is -1,073,741,824. The code shifts again only while the copy is at least that.

The one answer that does not fit

Which division has a result too big for an int? Only -2,147,483,648 / -1, whose true answer 2,147,483,648 is one more than the largest int. The statement asks for 231 - 1 in that case, which is Integer.MAX_VALUE, so the code returns it before doing any work.

Java Solution

The method divide works in these steps:

  1. First, if dividend is Integer.MIN_VALUE and divisor is -1, return Integer.MAX_VALUE.
  2. Record in negative whether exactly one of the inputs is below zero.
  3. Turn both inputs negative: a holds what is left of the dividend, and b holds the divisor.
  4. Start quotient at 0, and run an outer loop while a <= b, that is, while what is left still holds the divisor. Each turn of that loop is one round.
  5. Inside a round, multiple starts at b and count at 1. An inner loop shifts both left by one place while the shifted copy still fits in a and multiple is at least Integer.MIN_VALUE >> 1.
  6. Take multiple away from a and add count to quotient.
  7. When no round is left, return quotient, turned negative if negative is true.

The main method runs both examples, a few cases with zero, Integer.MAX_VALUE and Integer.MIN_VALUE, and then compares divide with Java's own / operator on a million random pairs.

Java
import java.util.Random;

public class DivideTwoIntegers {

    public static int divide(int dividend, int divisor) {
        if (dividend == Integer.MIN_VALUE && divisor == -1) {
            return Integer.MAX_VALUE;         // 2^31 does not fit in an int
        }
        boolean negative = (dividend < 0) != (divisor < 0);

        // work with negative numbers: -2^31 has no positive partner in an int
        int a = dividend > 0 ? -dividend : dividend;
        int b = divisor > 0 ? -divisor : divisor;

        int quotient = 0;
        while (a <= b) {                      // what is left still holds the divisor
            int multiple = b;                 // the divisor shifted left k places
            int count = 1;                    // 1 shifted left k places, that is 2^k
            // shift again while the result stays within a and cannot overflow
            while (multiple >= (Integer.MIN_VALUE >> 1) && a <= (multiple << 1)) {
                multiple <<= 1;
                count <<= 1;
            }
            a -= multiple;
            quotient += count;
        }
        return negative ? -quotient : quotient;
    }

    public static void main(String[] args) {
        System.out.println("10 / 3 = " + divide(10, 3));
        System.out.println("7 / -3 = " + divide(7, -3));
        System.out.println("-7 / -3 = " + divide(-7, -3));
        System.out.println("0 / 5 = " + divide(0, 5));
        System.out.println("1 / MIN_VALUE = " + divide(1, Integer.MIN_VALUE));
        System.out.println("MAX_VALUE / 1 = " + divide(Integer.MAX_VALUE, 1));
        System.out.println("MIN_VALUE / 1 = " + divide(Integer.MIN_VALUE, 1));
        System.out.println("MIN_VALUE / 2 = " + divide(Integer.MIN_VALUE, 2));
        System.out.println("MIN_VALUE / -1 = " + divide(Integer.MIN_VALUE, -1));

        Random random = new Random(42);
        int mismatches = 0;
        for (int i = 0; i < 1000000; i++) {
            int x = random.nextInt();
            int y = random.nextInt() >> random.nextInt(32);   // small and large divisors
            if (y == 0 || (x == Integer.MIN_VALUE && y == -1)) {
                continue;
            }
            if (divide(x, y) != x / y) {
                mismatches++;
            }
        }
        System.out.println("random pairs compared with /: mismatches = " + mismatches);
    }
}

Running it prints:

Output
10 / 3 = 3
7 / -3 = -2
-7 / -3 = 2
0 / 5 = 0
1 / MIN_VALUE = 0
MAX_VALUE / 1 = 2147483647
MIN_VALUE / 1 = -2147483648
MIN_VALUE / 2 = -1073741824
MIN_VALUE / -1 = 2147483647
random pairs compared with /: mismatches = 0

Example 1 gives 3 and Example 2 gives -2, and -7 / -3 = 2 shows two negative inputs making a positive result. For 0 / 5 and 1 / MIN_VALUE, what is left never holds the divisor, so no round runs and the answer is 0.

The line MAX_VALUE / 1 = 2147483647 is the division that would take over two billion steps when taking away 1 at a time. Here it needs 31 rounds, one for each 1 bit of 2,147,483,647.

Look closely at MIN_VALUE / 1 = -2147483648. Its single round shifts count 31 places to 231, which does not fit and wraps around to -2,147,483,648. Negating that value gives -2,147,483,648 back, which happens to be the right answer.

The line MIN_VALUE / -1 = 2147483647 comes from the first check, and the last line shows that the million random pairs all agree with Java's / operator.

Complexity

The work is a number of rounds, each with its own run of shifts.

  • Time: O((log n)²) for a dividend of size n, because there is one round for each 1 bit of the quotient, at most 31, and each round shifts its copy of the divisor at most 31 times. Keeping the shifted copies from the first round and reusing them would bring this down to O(log n), an optional improvement.
  • Space: O(1), because the method keeps only a handful of int variables (a, b, multiple, count and quotient) and uses no arrays or recursion.