A simple solution to calculate the longest length of binary gap of an integer in javascript.

Victor Onyango Oriko
1 min readJul 15, 2019

Problem

Given integer N, write an efficient function that returns the length of the longest binary gap within it.

Validate if the passed argument is an integer

Convert the integer into it’s binary form

Creating an Array of length of each binary item

This is the most interesting part of this solution. All we have to do is to split, the binary string we obtained above using ‘1’ of type string. This creates an array of either empty string or trailing zero(s). Our next step is to iterate through the array using Array.map() and subject each item to some condition so that the Array.map() only returns what we need. The condition should ensure that we only return the length of each item, in this case either empty string or zeros, if the value at the next index (current index plus 1) within the array is not undefined. Otherwise, if the value of the next index is undefined, we return 0;

Calculating the longest length of the binary gap

This is the last stage in this solution and it involves selecting the biggest number in the new array of lengths we have just created above. We are achieving this by using prototype.apply method of the Math Object.

Using our solution

We can now call our solution() function and pass to it any integer. I have tested the function with a number of random integers and the result is pretty impressive. This solution is short and clear.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Victor Onyango Oriko
Victor Onyango Oriko

Written by Victor Onyango Oriko

Senior Software Engineering Lead | Microsoft

Responses (5)

Write a response