Problem Description
Given two integers left and right that represent a range [left, right], compute the bitwise AND of all numbers in the range. The result should include only those bits that remain 1 across every number within the range.
Key Insights
- The bitwise AND operation only retains a bit if that bit is 1 in every number in the given range.
- The key observation is that the range of numbers will eventually force a bit position to flip from 1 to 0; hence, only the common prefix (the leftmost bits that do not change when moving from left to right) contributes to the final result.
- The solution involves shifting both left and right until they match, tracking the number of shifts, and then shifting back to obtain the common bits.
Space and Time Complexity
Time Complexity: O(log n), where n is the number represented by right, since we process a fixed number of bits (typically 32 bits for 32-bit integers). Space Complexity: O(1), since only a few integer variables are used.
Solution
The main idea is to discard the differing bits between left and right. We do this by shifting both numbers to the right until they become equal, which effectively removes the non-common bits at the right. The number of shifts performed tells us how many trailing zeros must be added back by shifting left. This approach efficiently finds the common prefix shared by both numbers, which represents the bitwise AND of all numbers in the given range.
Data Structures Used:
- Only integer variables are used.
Algorithmic Approach:
- While left is not equal to right, right-shift both left and right (i.e., remove the least significant bit).
- Count the number of shifts performed.
- Once left equals right, shift back to the left by the counted amount to restore the common prefix in its original bit positions.
- The final number is the bitwise AND of all numbers in the range.