DEV Community

kingsley Goodluck
kingsley Goodluck

Posted on

Codility Test Question

Hi guys, i've been struggling to get to complete this codility question.
**A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

Write a function:

function solution(N);

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..2,147,483,647].**

After series of failing, i finally came up with a solution. wont lie, it was frustrating at first, even the sample code i got online didn't work.

well i finally found a way to solve the test.

Below you'll find my code.

function solution(N) {
  // write your code in JavaScript (Node.js 8.9.4)
  let base = N.toString(2);
  let result = 0; //initialize to 0
  let t = 0;
  let array = [];

  for (let n in base) {
    let b = base[n]; 
    if (b == 1) {
      if (t >= 0) {
        array.push(result);
        result = 0;
        t = 0;
      } else {
        t += 1;
      }
    } else {
      result = result + 1;
    }
  }

  return array.reduce((a, b) => Math.max(a, b), -Infinity);
}

Enter fullscreen mode Exit fullscreen mode

If you're a software developer, i'll highly recommend you sign up on codility and have yourself some code challenges. You might never know logical you are in solving problems until you try most of this test.

Top comments (1)

Collapse
 
kyrolosmagdy profile image
Kyrolos

Yes, that makes the two of us, yet I found this awesome solution that uses regEx to solve it:
`function solution(N: number): number {
// Implement your solution here

return Math.max(...N.toString(2).split(/^0+|1+|0+$/).map(s=>s.length));
Enter fullscreen mode Exit fullscreen mode

}`

I uses TypeScript, yet I love this one.