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
Binary Gap Problem OverviewInput: n = 22 → Binary: 1011010110Gap = 1Gap = 0Maximum Gap Found: 2
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
Asked in
Google 12 Microsoft 8 Apple 5
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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