Skip to main content

Command Palette

Search for a command to run...

Codility - BinaryGap - JavaScript

Codility BinaryGap problem solved in JavaScript

Updated
2 min read
Codility - BinaryGap - JavaScript
A
Systems Architect. Software Engineer. Full Stack Developer. Architect of Chaos, mastering cloud, legacy, and light.

🧠 Binary Gap – Explained Line by Line

The Binary Gap problem asks to find the longest sequence of zeros surrounded by ones in the binary representation of a given positive integer N.

Example:
N = 529 → Binary: 1000010001 → Gaps: 0000, 000 → Longest = 4

Here's the code:

function solution(N) {
    let binary = N.toString(2);

    let gaps = binary.split('1').slice(1, -1);

    if (gaps.length === 0) return 0;

    let longestGap = gaps.reduce((acc, gap) => acc.length > gap.length ? acc : gap);

    return longestGap.length;
}

💡 Code Breakdown

let binary = N.toString(2);

  • Converts the number N to a binary string using base-2.

let gaps = binary.split('1').slice(1, -1);

  • Splits the binary string at each 1, creating an array of zeros between them.

  • The .slice(1, -1) removes the potential leading/trailing zeros that are not enclosed by 1s (i.e., not valid gaps).

if (gaps.length === 0) return 0;

  • Quick exit if no valid gaps exist.

let longestGap = gaps.reduce((acc, gap) => acc.length > gap.length ? acc : gap);

  • Iterates through all gaps to find the longest one based on .length.

return longestGap.length;

  • Returns the length of the longest valid binary gap.

🧩 Additional Notes

  • The task ensures N ∈ [1, 2,147,483,647] → no need to validate the range.

  • The .reduce() approach avoids unnecessary sorting or loops.

  • This solution runs in O(log N) time, proportional to the binary size of N — efficient and clean.

🔗 BinaryGap, from Lesson 1 – Iterations on Codility:
https://app.codility.com/programmers/lessons/1-iterations/binary_gap/