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:
1
💡 Note:
22 in binary is 10110. The gaps between consecutive 1's are: between positions 0 and 2 (gap = 1), between positions 2 and 3 (gap = 0). Maximum gap is 1.
Example 2 — No Gap
$
Input:
n = 6
›
Output:
0
💡 Note:
6 in binary is 110. The gap between consecutive 1's at positions 0 and 1 is 0. Maximum gap is 0.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code