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])])
'Computer Science > 알고리즘' 카테고리의 다른 글
[Codility] 3. Complexity (1) | 2023.12.16 |
---|---|
[Codility] 2. Array (1) | 2023.12.16 |
Dijkstra 다익스트라, Prim과의 차이점 (1) | 2023.12.07 |
최소신장트리 MST, Kruskal(크루스칼), Prim(프림), Sollin(솔린) (1) | 2023.12.07 |
그래프, 그래프탐색(DFS, BFS) 이론정리 (2) | 2023.12.07 |