Given a positive integer N, find the longest distance (number of consecutive zeros) between two successive 1 bits in the binary representation of N. The distance is measured as the number of zeros between the two 1s.
Traverse the binary representation from LSB to MSB (or vice versa). Track the position of the last seen 1 and when you encounter another 1, compute the gap between positions and update the maximum.
classSolution {
public:int binaryGap(int N) {
int last =-1;
int maxGap =0;
int pos =0;
while (N >0) {
if ((N &1) ==1) {
if (last !=-1) maxGap = std::max(maxGap, pos - last -1);
last = pos;
}
N >>=1;
++pos;
}
return maxGap;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
packagemainfuncbinaryGap(Nint) int {
last:=-1maxGap:=0pos:=0forN > 0 {
if (N&1) ==1 {
iflast!=-1 {
gap:=pos-last-1ifgap > maxGap { maxGap = gap }
}
last = pos }
N>>=1pos++ }
returnmaxGap}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintbinaryGap(int N) {
int last =-1;
int maxGap = 0;
int pos = 0;
while (N > 0) {
if ((N & 1) == 1) {
if (last !=-1) maxGap = Math.max(maxGap, pos - last - 1);
last = pos;
}
N >>= 1;
pos++;
}
return maxGap;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defbinary_gap(self, N: int) -> int:
last =-1 max_gap =0 pos =0while N >0:
if (N &1) ==1:
if last !=-1:
max_gap = max(max_gap, pos - last -1)
last = pos
N >>=1 pos +=1return max_gap
Iterate over the positions of set bits by repeatedly clearing the least-significant 1 using N &= (N - 1). Track the index of each cleared bit and compute gaps between successive set-bit positions.
⏰ Time complexity: O(k) where k is the number of set bits (worst-case O(log N)). Using bit intrinsics makes this efficient.
🧺 Space complexity: O(1).
Notes
This problem appears on LeetCode as “Binary Gap” and on Codility under the same name; solutions above cover both platforms (differences are in input sizes/details only).