Given two integers left
and right
that represent the range [left, right]
, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7 Output: 4
Example 2:
Input: left = 0, right = 0 Output: 0
Example 3:
Input: left = 1, right = 2147483647 Output: 0
Constraints:
0 <= left <= right <= 231 - 1
The problem asks to find the bitwise AND of all numbers within a given range [left, right]. A naive approach would involve iterating through all numbers in the range and performing the bitwise AND operation cumulatively. However, this approach has a time complexity of O(right - left), which can be inefficient for large ranges.
The solution presented leverages a crucial observation: The bitwise AND of all numbers in the range [left, right] will always be less than or equal to the leftmost number in the range (left). Furthermore, the result will always have trailing zeros. The algorithm efficiently finds this result by repeatedly performing a bitwise AND operation between right
and right - 1
until left
equals right
.
Algorithm:
The core idea is that subtracting 1 from a number clears the least significant set bit. By repeatedly applying this operation to the right bound, we effectively clear all bits that are not set in all numbers in the range [left, right].
Iteration: The while
loop continues as long as left
is less than right
.
Bit Manipulation: Inside the loop, right &= (right - 1)
performs the bitwise AND operation between right
and right - 1
. This clears the least significant set bit of right
. This is repeated until there are no bits that change across all numbers in the range.
Result: Once the loop terminates (left == right
), right
holds the bitwise AND of all numbers in the initial range. This value is returned as the result.
Time and Space Complexity:
Time Complexity: The number of iterations of the while
loop is determined by the number of trailing bits of right
which is at most log₂(right). Therefore, the time complexity is O(log n), where n is the right boundary of the range. This is significantly more efficient than a naive O(n) approach for large ranges.
Space Complexity: The algorithm uses a constant amount of extra space, regardless of the input size. Therefore, the space complexity is O(1).
Example Walkthrough (left = 5, right = 7):
left = 5
(binary 101), right = 7
(binary 111).right
becomes 7 & (7 - 1) = 7 & 6 = 6
(binary 110).right
becomes 6 & (6 - 1) = 6 & 5 = 4
(binary 100).left = 5
and right = 4
. The loop condition left < right
is false.right
, which is 4.The code provided in various languages implements this algorithm efficiently. Each version is functionally equivalent, showcasing the algorithm's simplicity and adaptability across different programming languages.