Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created February 22, 2026 18:04
Show Gist options
  • Select an option

  • Save tatsuyax25/7aeae5f30f5432d2aadd65278e206fa2 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/7aeae5f30f5432d2aadd65278e206fa2 to your computer and use it in GitHub Desktop.
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)
/**
* @param {number} n
* @return {number}
*/
var binaryGap = function(n) {
// Convert the number to its binary string representation.
// Example: 22 -> "10110"
const binary = n.toString(2);
// This will store the index of the *previous* '1' we saw.
// We start with null because we haven't seen any '1' yet.
let prevOneIndex = null;
// This will track the maximum distance found so far.
let maxDistance = 0;
// Loop through each character in the binary string.
for (let i = 0; i < binary.length; i++) {
// We're only interested in positions where the bit is '1'.
if (binary[i] === '1') {
// If we've seen a previous '1', compute the distance.
if (prevOneIndex !== null) {
const distance = i - prevOneIndex;
// Update the maximum distance if this one is larger.
maxDistance = Math.max(maxDistance, distance);
}
// Update prevOneIndex to the current index of '1'.
prevOneIndex = i;
}
}
// If there were fewer than two '1's, maxDistance will still be 0.
return maxDistance;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment