Leetcode 201. Bitwise AND of Numbers Range
LeetCode Problem 201: Bitwise AND of Numbers Range
Given two integers left
and right
, return the bitwise AND of all numbers in the inclusive range [left, right]
.
left
and right
?
0 <= left <= right <= 2^31 - 1
left
is always less than or equal to right
?
0 <= left <= right
.0
to 1
or 1
to 0
within the range.1
across all numbers in the range [left, right]
will contribute to the final result.left
and right
such that they share the common prefix of bits.left
and right
until they are equal because the differing bits beyond the common prefix will yield 0
when ANDed.shift
counter to count the number of right shifts.left
and right
until they become equal.Here is the C++ code implementing this strategy:
class Solution {
public:
int rangeBitwiseAnd(int left, int right) {
int shift = 0;
// Find the common prefix
while (left < right) {
left >>= 1;
right >>= 1;
shift++;
}
// Left shift the result back to its original position
return left << shift;
}
};
The time complexity of the algorithm:
left
equal to right
depends on the number of bits in right
. In the worst case, this would be around ( O(\log N) ), where ( N ) is the value of right
.The space complexity is ( O(1) ) as we are only using a few extra integer variables for shifting operations.
left
and right
until they are the same, we effectively find the common bit prefix.This solution efficiently finds the bitwise AND of all numbers in the given range using bit manipulation.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?