Bitwise AND of Numbers Range
Bitwise AND of Numbers Range
Bit Manipulation
Problem Statement
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Example
Example 1:
Input: left = 5, right = 7
Output: 4
Explanation:
5 = 0101
6 = 0110
7 = 0111
The bitwise AND of these numbers is 4 (0100).
Solution (Common Prefix)
The key insight is that the bitwise AND of a range of numbers is determined by their common most significant bits. Any bit that flips from 0 to 1 (or vice versa) within the range will result in a 0 in that position in the final AND result.
Therefore, the problem reduces to finding the common "left-side" prefix of the binary representations of left and right.
Algorithm Steps
- Initialize a shiftcounter to 0.
- While leftis not equal toright:
- Right-shift both leftandrightby 1.
- Increment the shiftcounter.
- Once leftandrightare equal, you have found the common prefix.
- Left-shift the common prefix (left) by theshiftcount to get the final result.
Left
00000101
Right
00000111
Shifts
0
Initial state: left = 5, right = 7
Bitwise AND of Numbers Range Solution