Bitwise AND of Numbers Range - Problem
You're given two integers
The bitwise AND operation compares each bit position of the numbers and returns 1 only if all numbers have 1 in that position. For example, if we have range [5, 7], we need to compute
Key Challenge: The range could be very large (up to 231 - 1), so iterating through every number would be too slow! You need to find a clever bit manipulation approach.
Example: For range [5, 7]:
• 5 = 101₂
• 6 = 110₂
• 7 = 111₂
• 5 & 6 & 7 = 100₂ = 4
left and right that define a range [left, right]. Your task is to find the bitwise AND of all numbers in this range, inclusive.The bitwise AND operation compares each bit position of the numbers and returns 1 only if all numbers have 1 in that position. For example, if we have range [5, 7], we need to compute
5 & 6 & 7.Key Challenge: The range could be very large (up to 231 - 1), so iterating through every number would be too slow! You need to find a clever bit manipulation approach.
Example: For range [5, 7]:
• 5 = 101₂
• 6 = 110₂
• 7 = 111₂
• 5 & 6 & 7 = 100₂ = 4
Input & Output
example_1.py — Basic Range
$
Input:
left = 5, right = 7
›
Output:
4
💡 Note:
The bitwise AND of 5 & 6 & 7 is 4. In binary: 101₂ & 110₂ & 111₂ = 100₂ = 4. Only the bit at position 2 remains 1 across all numbers.
example_2.py — Large Range
$
Input:
left = 0, right = 0
›
Output:
0
💡 Note:
When left equals right, the result is simply that number. 0 & 0 = 0.
example_3.py — Power of 2 Range
$
Input:
left = 1, right = 2147483647
›
Output:
0
💡 Note:
In such a large range, all bit positions will have both 0s and 1s appearing, so the final AND result is 0. This demonstrates why the optimal approach is necessary.
Constraints
- 0 ≤ left ≤ right ≤ 231 - 1
- Range can be very large - brute force will timeout
- Both left and right are inclusive in the range
Visualization
Tap to expand
Understanding the Visualization
1
Bit Cycling
In any range, rightmost bits cycle through 0 and 1
2
AND Effect
When ANDing cycling bits, result becomes 0
3
Common Prefix
Only stable prefix bits survive the AND operation
4
Pattern Recognition
Find where left and right first differ
Key Takeaway
🎯 Key Insight: In any range, only the common binary prefix of the boundaries survives the AND operation. Once bits start differing, all subsequent positions become 0.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code