Bitwise AND of Numbers Range

Find the bitwise AND of every number from left to right by keeping the bits the two ends share at the top.

Given two integers left and right with 0 <= left <= right <= 2^31 - 1, return the bitwise AND of every number from left to right, both ends included.

Example 1
Input: left = 5, right = 7
Output: 4
Explanation: 5 (101) AND 6 (110) AND 7 (111) = 100 = 4.
Example 2
Input: left = 1, right = 2147483647
Output: 0
Solution

The Idea

A computer keeps every whole number as a row of bits, zeros and ones. We number the positions from the right, starting at 0, so 5 is 101, with a 1 in positions 2 and 0. The AND of two numbers compares them position by position and writes a 1 only where both numbers have a 1.

Take Example 1. 5 is 101 and 6 is 110, so they share a 1 only in position 2, and their AND is 100, which is 4. ANDing that with 7, 111, keeps 100, so the answer is 4.

Example 2 is the same task on a much bigger scale: the range from 1 to 2,147,483,647 holds more than two billion numbers. Do we really have to AND them one by one, or can left and right alone tell us the answer?

A bit of the answer is 1 only if every number in the range has a 1 in that position. One number with a 0 there is enough to clear it. When we count upward, position 0 flips on every step, position 1 every two steps, position 2 every four. So low positions change often and high positions rarely.

Look at the picture below. It shows the range from 26 to 30, with the bit positions 4 to 0 across the top.

The numbers 26 to 30 in binary, with bit positions 4 to 0. All five start with 11 in positions 4 and 3, the common prefix. 26 and 30 first differ in position 2. 26 has 0 in position 2 and 28 has 0 in positions 1 and 0, so the AND of all is 11000, which is 24.

In positions 4 and 3, every row holds 1 1. The two ends, 26 and 30, agree there, so counting from one to the other never touches those bits. The leading bits on which the two ends agree are called their common prefix, shaded teal in the picture.

In position 2, labelled "first difference", 26 has a 0 and 30 has a 1. That 0 in 26 already clears position 2 in the answer. On its way from 26 up to 30, the count must turn position 2 from 0 into 1. It does so at 28, 11100, where all the positions below are 0, as the label "28 has 0 in positions 1 and 0" shows.

So every position after the common prefix gets a 0 from some number in the range. The answer is the common prefix followed by zeros: 11 and then 000, which is 11000, or 24, as in the row labelled "AND of all".

Solution Approach

Turning the idea into code means three decisions: whether to AND the numbers one by one, how to find the common prefix, and how to put it back in its place. Clearing low bits from right alone is an optional second way to reach the same answer.

ANDing every number

Why not loop from left to right and AND each number into the result? It gives the right answer, but the loop takes one step per number. For Example 2 that is more than two billion steps to produce a 0.

That loop has a second problem when right is 2147483647, the largest int. A counter i of type int can never be larger than that. Adding 1 to it gives -2147483648, so the condition i <= right stays true and the loop does not end.

Finding the common prefix

How do we find the common prefix without checking the bits one at a time from the top? Shift both numbers one position to the right. In Java, x >> 1 drops the bit in position 0 and moves every other bit down one position.

For 26 and 30 that gives 13 (1101) and 15 (1111), still different. One more shift gives 6 (110) and 7 (111), and a third gives 3 and 3, both 11. Once the two are equal, the bits that are left are the common prefix, and a counter records that it took three shifts.

How many shifts can it take at most? A Java int has 32 bits and stores negative numbers in two's complement form, where position 31, the leftmost, is 1 for a negative number. Here neither input is negative, so position 31 is 0. After 31 shifts both numbers are 0 and therefore equal.

Putting the prefix back in place

The prefix 11 now sits three positions too low. Shifting it left by the counted number, 3 << 3, moves it back up and fills the three freed positions with zeros. The result is 11000, which is 24.

Another way: clearing the lowest 1 bit (optional)

Is there a way that touches only right? The expression right & (right - 1) clears the lowest 1 bit of right. Subtracting 1 turns that bit into 0 and the zeros below it into ones, and the AND keeps everything else. Removing one 1 bit per step like this is often credited to Brian Kernighan.

Java
while (right > left) {
    right &= right - 1;   // clear the lowest 1 bit of right
}

After the loop, right holds the answer. For 26 and 30, right goes from 30 (11110) to 28 (11100), which is still larger than 26. Then it goes to 24 (11000), which is not, so the loop stops with 24. For Example 1 it goes from 7 to 6 to 4.

Java Solution

The method rangeBitwiseAnd works in these steps:

  1. First, set a counter shift to 0. It counts how many low bits have been dropped.
  2. While left and right are different, shift both one position to the right with >>= 1 and add 1 to shift.
  3. When the two are equal, left holds the common prefix. Return left << shift, the prefix moved back up with zeros after it.

The main method uses a helper named show, which calls rangeBitwiseAnd and prints the answer in decimal and in binary. It shows both examples, the range 26 to 30 from the picture, a range of one number, a range starting at 0, and the two largest int values. Then it compares the method with the one-by-one AND for every range inside 0 to 299.

Java
public class BitwiseAndOfNumbersRange {

    public static int rangeBitwiseAnd(int left, int right) {
        int shift = 0;
        while (left != right) {   // they still differ in some lower bit
            left >>= 1;           // drop the lowest bit of both
            right >>= 1;
            shift++;
        }
        return left << shift;     // the common prefix, followed by shift zeros
    }

    static void show(int left, int right) {
        int answer = rangeBitwiseAnd(left, right);
        System.out.println("range [" + left + ", " + right + "] -> " + answer
                + " = " + Integer.toBinaryString(answer) + " in binary");
    }

    public static void main(String[] args) {
        show(5, 7);
        show(1, Integer.MAX_VALUE);
        show(26, 30);
        show(12, 12);
        show(0, 9);
        show(Integer.MAX_VALUE - 1, Integer.MAX_VALUE);

        boolean allMatch = true;           // compare with ANDing every number, one by one
        for (int left = 0; left < 300; left++) {
            for (int right = left; right < 300; right++) {
                int slow = left;
                for (int x = left + 1; x <= right; x++) {
                    slow &= x;
                }
                if (slow != rangeBitwiseAnd(left, right)) {
                    allMatch = false;
                }
            }
        }
        System.out.println("matches the one-by-one AND for all ranges in 0..299: " + allMatch);
    }
}

Running it prints:

Output
range [5, 7] -> 4 = 100 in binary
range [1, 2147483647] -> 0 = 0 in binary
range [26, 30] -> 24 = 11000 in binary
range [12, 12] -> 12 = 1100 in binary
range [0, 9] -> 0 = 0 in binary
range [2147483646, 2147483647] -> 2147483646 = 1111111111111111111111111111110 in binary
matches the one-by-one AND for all ranges in 0..299: true

Look at the third line: the range 26 to 30 gives 24, 11000, the common prefix 11 with three zeros, just as in the picture. Example 2 gives 0 because 1 and 2147483647 share no 1 bit at the top. They only become equal once both have been shifted down to 0.

The range 12 to 12 gives 12 itself, since the two ends are equal from the start and the loop never runs. The range 0 to 9 gives 0, because 0 has no 1 bits to share.

The two ends 2147483646 and 2147483647 differ only in position 0. One shift makes the two equal, and the answer keeps all 30 ones above it, ending in a single 0. The last line says the method agreed with the slow loop on all 45,150 ranges from 0 to 299.

Complexity

The method never visits the numbers between the two ends; it only drops bits until left and right agree.

  • Time: O(1), because each round of the loop drops one bit, and two non-negative int values are equal after at most 31 rounds, however many numbers lie between them.
  • Space: O(1), because the method keeps only its two inputs and the shift counter.