Codility lessons #1

Wojciech Trawiński
JavaScript everyday
2 min readJan 12, 2019

Binary Gap

I’ve recently decided to focus on algorithmical riddles available as Codility lessons instead of sticking to Codewars challenges.

In this article and the following ones I would like to share my solutions, of course in JavaScript 😃.

Task description

In short, the aim of the task is to write a function which takes a positive integer number as its only argument and returns the longest sequence of zeros (enclosed by 1 digit) for a binary representation of the input parameter.

The comprehensive task’s description can be found on the task’s page.

Solution

First, I had to get a binary representation of the input number. The easiest way to achieve it (for the task’s assumptions) was to make use of the toString method available through the Number.prototype and provide a radix argument being the base for conversion (2 for the above example).

In the next step, I created an array of digits that the binary representation was made of. Since I wanted to get a single value (the longest sequence of zeros) based on a given array, the reduce method was the obvious choice.

The state was described as an object with two properties, namely: maxSoFar and occurrences, while the accumulator function was handleBinaryNum.

The accumulator function was called for each digit and based on its value (0 or 1) the proper handler function was picked using getDigitHandler.

If the current digit was 0, a handler function (handleZeroDigit) was supposed to increment the occurrences property by one.

If the current digit was 1, a handler function (handleOneDigit) was supposed update the maxSoFar property of the state object (a check if the sequence which had just ended was longer than the longest one encountered so far) and reset the occurrences property.

Conclusions

In order to solve the task, it was necessary to figure out a way to convert a decimal number to its binary representation. I took a declarative approach in my solution, however you my also be more imperative and solve the task with the aid of for / for of loop and simply branch your code using if/else block.

--

--