Binary Gap - Problem
Given a positive integer n, find and return the longest distance between any two adjacent 1's in the binary representation of n.
If there are no two adjacent 1's, return 0.
Two 1's are adjacent if there are only 0's separating them (possibly no 0's). The distance between two 1's is the absolute difference between their bit positions.
For example, the two 1's in "1001" have a distance of 3.
Input & Output
Example 1 — Basic Gap
$
Input:
n = 22
›
Output:
2
💡 Note:
22 in binary is 10110. The gaps between consecutive 1's are: between positions 1 and 4 (gap = 2). Maximum gap is 2.
Example 2 — No Gap
$
Input:
n = 6
›
Output:
1
💡 Note:
6 in binary is 110. The gap between consecutive 1's at positions 1 and 2 is 0. But we also have trailing zeros, so gap is 1.
Example 3 — Power of 2
$
Input:
n = 8
›
Output:
0
💡 Note:
8 in binary is 1000. There's only one 1, so no adjacent 1's exist. Return 0.
Constraints
- 1 ≤ n ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Integer n = 22
2
Convert
Binary representation: 10110
3
Find Gaps
Measure distances between consecutive 1's
Key Takeaway
🎯 Key Insight: Track positions of consecutive 1 bits and calculate the maximum distance between them
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code