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 leftright0 <= left <= right <= 2^31 - 1leftright
Example 1
Output: 4
Explanation: 5 (101) AND 6 (110) AND 7 (111) = 100 = 4.
Example 2
Output: 0
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
Take Example 1. 5 is 101110100111100
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 leftright
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.
In positions 4 and 3, every row holds 1 1
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
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: 1100011000
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
ANDing every number
Why not loop from leftright
That loop has a second problem when rightintiinti <= right
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
For 26 and 30 that gives 13 (1101111111011111
How many shifts can it take at most? A Java int
Putting the prefix back in place
The prefix 113 << 311000
Another way: clearing the lowest 1 bit (optional)
Is there a way that touches only rightright & (right - 1)right
while (right > left) {
right &= right - 1; // clear the lowest 1 bit of right
}
After the loop, rightright111101110011000
Java Solution
The method rangeBitwiseAnd
- First, set a counter
to 0. It counts how many low bits have been dropped.shift - While
andleft are different, shift both one position to the right withright and add 1 to>>= 1 .shift - When the two are equal,
holds the common prefix. Returnleft , the prefix moved back up with zeros after it.left << shift
The mainshowrangeBitwiseAndint
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:
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, 1100011
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 leftright
- Time: O(1), because each round of the loop drops one bit, and two non-negative
values are equal after at most 31 rounds, however many numbers lie between them.int - Space: O(1), because the method keeps only its two inputs and the
counter.shift