Divide Two Integers
Divide one int by another using only shifts, additions and subtractions, rounding toward zero.
Given two integers dividenddivisordividenddivisor
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
Output: 3
Explanation: 10 / 3 = 3.333..., rounded toward zero to 3.
Example 2
Output: -2
Explanation: 7 / -3 = -2.333..., rounded toward zero to -2.
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 int0011<<3 << 101103 << 21100
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.
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
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
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 int11111111111111111111111111111101
This gives one more negative value than positive ones. The smallest, -2,147,483,648 or Integer.MIN_VALUEMath.abs(Integer.MIN_VALUE)
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-6 << 1long
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>>Integer.MIN_VALUE >> 1
The one answer that does not fit
Which division has a result too big for an intintInteger.MAX_VALUE
Java Solution
The method divide
- First, if
isdividend andInteger.MIN_VALUE is -1, returndivisor .Integer.MAX_VALUE - Record in
whether exactly one of the inputs is below zero.negative - Turn both inputs negative:
holds what is left of the dividend, anda holds the divisor.b - Start
at 0, and run an outer loop whilequotient , that is, while what is left still holds the divisor. Each turn of that loop is one round.a <= b - Inside a round,
starts atmultiple andb at 1. An inner loop shifts both left by one place while the shifted copy still fits incount anda is at leastmultiple .Integer.MIN_VALUE >> 1 - Take
away frommultiple and adda tocount .quotient - When no round is left, return
, turned negative ifquotient is true.negative
The mainInteger.MAX_VALUEInteger.MIN_VALUEdivide/
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:
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 = 20 / 51 / MIN_VALUE
The line MAX_VALUE / 1 = 2147483647
Look closely at MIN_VALUE / 1 = -2147483648count
The line MIN_VALUE / -1 = 2147483647/
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
variables (int ,a ,b ,multiple andcount ) and uses no arrays or recursion.quotient