Bitwise AND of Numbers Range
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
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
Input: left = 5, right = 7
Output: 4
Input: left = 0, right = 0
Output: 0
Approach 1
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
⏱ O(N) - Where $N$ is the number of integers in the range.💾 O(1) - Constant space.
Approach 2
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.⏱ $O(1)$ - Maximum of 32 shifts.💾 $O(1)$
Approach 3
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
⏱ O(1) - Max 32 iterations.💾 O(1) - Constant space.
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
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.