Computer Science/알고리즘

[Codility] 1. Iteration

hyunjin 2023. 12. 16. 22:36

1.1 BinaryGap

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.

Write a function 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.

 

양의 정수 N 내의 이진 갭은 N의 이진 표현에서 양쪽 끝에 하나로 둘러싸인 연속적인 0의 최대 시퀀스입니다.

양의 정수 N이 주어지면 가장 긴 이진법의 길이를 반환하는 함수를 쓰시오. N이 이진법의 간격을 포함하지 않으면 함수는 0을 반환해야 합니다.

def solution(N):
    tmp = []
    i = 0
    while N != 0:
        if N%2 == 1:
            tmp += [i]
        N = N // 2
        i+=1
    return max([0]+[i-j-1 for i, j in zip(tmp[1:], tmp[:-1])])