๐ Beginner-Friendly Guide 'Binary Gap' - Problem 868 (C++, Python, JavaScript)
Source: Dev.to
Problem Statement
You are given a positive integer n.
Return the longest distance between any two adjacent 1 bits in the binary representation of n.
If there is no such pair, return 0.
Approach
Traverse the binary representation of n from right to left, counting the number of bits since the last seen 1.
- Keep a distance counter
d. - Initialize
dwith a sentinel value (e.g.,-32) to indicate that the first1has not been encountered yet. - While
nis greater than0:- If the current leastโsignificant bit is
1:- Update the answer with
max(answer, d). - Reset
dto0to start counting the next gap.
- Update the answer with
- Otherwise, increment
d. - Shift
nright (or divide by2) to process the next bit.
- If the current leastโsignificant bit is
Using a sentinel value prevents the first 1 from incorrectly contributing to the maximum distance.
Examples
Example 1
- Input:
22 - Binary:
10110
| Position (from right) | Bit | Action |
|---|---|---|
| 2 | 1 | start counting |
| 3 | 1 | distance = 1 |
| 5 | 1 | distance = 2 (max) |
Result: 2
Example 2
- Input:
8 - Binary:
1000
Only one 1 is present, so no pair exists.
Result: 0
Code
C++
class Solution {
public:
int binaryGap(int n) {
int ans = 0;
// d represents the distance from the last seen 1.
// Starting at -32 ensures the first 1 found doesn't trigger a max distance update.
for (int d = -32; n > 0; n /= 2, ++d) {
if (n % 2 == 1) {
ans = std::max(ans, d);
d = 0;
}
}
return ans;
}
};
Python
class Solution:
def binaryGap(self, n: int) -> int:
ans = 0
d = -32 # sentinel value
while n > 0:
if n % 2 == 1:
ans = max(ans, d)
d = 0
n //= 2
d += 1
return ans
JavaScript
/**
* @param {number} n
* @return {number}
*/
var binaryGap = function(n) {
let ans = 0;
let d = -32; // sentinel value
while (n > 0) {
if (n % 2 === 1) {
ans = Math.max(ans, d);
d = 0;
}
n = Math.floor(n / 2);
d++;
}
return ans;
};
Key Concepts
- Bit Manipulation: Extract bits using modulo (
% 2) and shift/divide by2. - State Tracking: A sentinel value (e.g.,
-32) handles the initial case without extra conditionals. - Efficiency: The algorithm runs in
O(log n)time, proportional to the number of bits inn, and usesO(1)extra space.
Understanding binary gaps is a useful exercise for lowโlevel problem solving, data compression, and network protocol design, where every bit matters.