class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
shift = 0
# Find the common prefix
while left < right:
left >>= 1
right >>= 1
shift += 1
return left << shift
class Solution {
public:
int rangeBitwiseAnd(int left, int right) {
int shift = 0;
while (left < right) {
left >>= 1;
right >>= 1;
shift++;
}
return left << shift;
}
};
class Solution {
public int rangeBitwiseAnd(int left, int right) {
int shift = 0;
while (left < right) {
left >>= 1;
right >>= 1;
shift++;
}
return left << shift;
}
}
var rangeBitwiseAnd = function(left, right) {
let shift = 0;
while (left < right) {
left >>= 1;
right >>= 1;
shift++;
}
return left << shift;
};
The "Bitwise AND of Numbers Range" problem asks you to compute the result of the bitwise AND operation on all integers in the inclusive range between two given integers, left
and right
. In other words, you need to find the value of left & (left + 1) & (left + 2) & ... & right
.
left
and right
are both non-negative integers, and left <= right
.
At first glance, you might consider iterating through every number from left
to right
and applying the bitwise AND operation. This brute-force approach works for small ranges, but quickly becomes infeasible for large ranges because it would require looping through potentially billions of numbers.
To optimize, we need to observe what happens to the bits during the AND operation. For any bit position, if that bit changes from 1 to 0 anywhere in the range, the result for that bit will be 0. Therefore, the only bits that remain set are those that are the same for every number in the range — in other words, the common prefix of left
and right
in binary.
The key insight is that the result of the bitwise AND is the common leftmost bits (prefix) shared by left
and right
. Any bit that differs between left
and right
(and all less significant bits) will be zeroed out in the final result.
left
is less than right
, right-shift both left
and right
by one bit. Keep track of the number of shifts.left
equals right
, we've found the common prefix. All differing bits to the right have been shifted off.This approach is efficient because it only requires as many iterations as there are bits in the numbers (at most 31 or 32 for typical integers), rather than looping through the entire range.
Example: left = 26
, right = 30
11010
11110
Let's follow the algorithm:
The AND of all numbers from 26 to 30 is 24.
right - left + 1
.
The "Bitwise AND of Numbers Range" problem can be solved efficiently by recognizing that only the common leftmost bits of left
and right
survive the AND operation across the range. By shifting both numbers right until they match, and then shifting the result back, we avoid iterating through the entire range. This insight leads to a concise, elegant, and highly efficient solution that works for even the largest allowed input sizes.