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.
In order to make code of finding out the binary gap of integer ‘N’, first of all we need to exchange from integer N to binary representation.
int to binary
There are several methods to change int into binary by python. bin
method is the most simple way, but we need to remove 0b
from result. So I select to use format(N, 'b)
.
def solution(N):
# int to binary
bin_N = format(N,'b')
print (bin_N)
solution(100) #1100100
find binary gap
Binary gap is the number of consecutive zeros between ones. We need to get rid of leading and trailing zeros.
def solution(N):
# int to binary
bin_gap = format(N,'b').strip('0')
print (bin_gap)
solution(100) #11001
Next step, I want to use split
method, because we need maximum value of consecutive zeros.
def solution(N):
# int to binary
bin_gap = format(N,'b').strip('0').split('1')
print (bin_gap)
solution(100) #['', '', '00', '']
Finally, we can make an output of binary gap using by max
and len
method.
def solution(N):
# int to binary
bin_gap = len(max(format(N,'b').strip('0').split('1')))
print (bin_gap)
solution(100) #2
Reference
https://app.codility.com/programmers/lessons/1-iterations/binary_gap/