Codility BinaryGap – Python Solution

This post is a Python solution to the Codility BinaryGap problem (Lesson 1 – Iterations) which scored 100%. Now, Let’s understand the problem first.

Codility BinaryGap Problem:

Find the longest sequence of zeros in the binary representation of an integer.

Although the problem is described quite elaborately at Codility, here is just an outline with an example.

Binary representation of number 101 is “1100101”.

bin(101).replace("0b", "")

Now, for this number, there are 2 binary gaps: one of length 2 and one of length 1. We need to write a function to get the longest binary gap and for this example, the function should return 2.

Python Solution:

The workaround is as below:

  • convert the number to its binary representation
  • loop through each integer one by one and mark the index of each 1 to a list
  • loop through the list, created above, to look for the largest gap
Assumptions:
  • N is an integer within the range [1..2,147,483,647].

Code:

Test Cases:

N = 1041
g = solution(N)
print(g)

The function returned : 5

N = 2147483647
g = solution(N)
print(g)

The function returned : 0

N = 1073741825
g = solution(N)
print(g)

The Function returned: 29

Conclusion:

Codility runs the solution for different test cases which are extremes an create a report with Test Results on Correctness and Performance. For this particular problem, Performance is not assessed.

Please leave a comment if the solution did not work for you. Or, Clap once if you think the post is helpful.

Check the below post for more python solution for codility challenges:

Codility CyclicRotation – Python Solution

Thank You!

3

Leave a Reply

Your email address will not be published. Required fields are marked *