Bitwise AND of Numbers Range
Master this topic with zero to advance depth.
Bitwise AND of Numbers Range
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Examples
Level I: Brute Force (Linear AND)
Intuition
Iterate from left to right and perform bitwise AND on all numbers. This is slow if the range is large.
Thought Process
- Initialize
res = left. - Iterate
ifromleft + 1toright. res &= i.- Return
res.
Pattern: Simulation
Level II: Iterative Shift (Pre-calculation)
Intuition
Shift both left and right rightward until they are identical. The bits that are removed are the ones that fluctuate within the range. Finally, shift the common prefix back to its original position.
Level III: Optimal (Common Prefix / Brian Kernighan)
Intuition
The bitwise AND of a range is the common prefix of the binary representations of the range's endpoints. Any bit that changes within the range will eventually become 0 in the final AND result.
Thought Process
- While
right > left:right = right & (right - 1)(clears the rightmost set bit).
- Alternatively, shift both numbers right until they are equal, then shift back.
Pattern: Bitwise Prefix Match
Detailed Dry Run
left=5(101), right=7(111) Iteration 1: right = 7 & 6 = 6 (110). 6 > 5. Iteration 2: right = 6 & 5 = 4 (100). 4 < 5. Stop. Result: 4
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.