Bitwise AND of Numbers Range - Problem

Given two integers left and right that represent the range [left, right], return 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 when all corresponding bits are 1, otherwise returns 0.

Example: For range [5, 7], we compute 5 & 6 & 7 = 4

Input & Output

Example 1 — Basic Range
$ Input: left = 5, right = 7
Output: 4
💡 Note: Binary: 5 (101) & 6 (110) & 7 (111) = 100 = 4. Only the leftmost bit stays 1 across all numbers.
Example 2 — Same Number
$ Input: left = 0, right = 0
Output: 0
💡 Note: When left equals right, the AND of a single number is the number itself: 0.
Example 3 — Large Range
$ Input: left = 1, right = 2147483647
Output: 0
💡 Note: Large range spans multiple bit positions, so all bits get zeroed out through the AND operations.

Constraints

  • 0 ≤ left ≤ right ≤ 231 - 1

Visualization

Tap to expand
Bitwise AND of Range [5, 7]Range:5, 6, 75 (binary):1016 (binary):1107 (binary):111Common bitDiffering bitsAND Result:100Binary 100 = Decimal 4Final Answer: 4
Understanding the Visualization
1
Input Range
Given left=5, right=7, find AND of all numbers
2
Binary Analysis
Compare binary representations to find common bits
3
AND Result
Only common prefix bits survive
Key Takeaway
🎯 Key Insight: Only the common binary prefix survives the AND operation across any range
Asked in
Google 15 Microsoft 12 Amazon 8
267.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen