본문 바로가기
Algorithm/Codility

[Codility] BinaryGap 파이썬 풀이

by daewooki 2024. 1. 23.
반응형

문제 링크: https://app.codility.com/programmers/lessons/1-iterations/

문제

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:

def 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].

 

 

0보다 큰 정수 N을 이진수로 변환한 후, 연속된 0의 길이 중 가장 큰 값을 반환하면 해결될 문제로 보입니다.

 

코드

1
2
3
4
5
6
7
8
9
10
def solution(N):
    binary = bin(N)[2:]
    arr = binary.strip("0").split("1")
    arr = [x for x in arr if x != '']
    
    if len(arr)<1:
        return 0
    else:
        arr_len = [len(x) for x in arr]
        return max(arr_len)
cs

 

 

함수의 동작을 아래와 같이 설명할 수 있습니다:

1. 정수 N을 이진수로 변환하고, 변환된 이진수 문자열에서 '0b'를 제외한 부분을 가져옵니다.

2. 이진수 문자열에서 양 끝의 0을 제거합니다.

3. 1로 나눠 리스트로 만듭니다.
4. 리스트에서 빈 문자열은 제거합니다.
5. 만약 생성된 리스트가 비어있다면, 0을 반환합니다.
6. 그렇지 않으면, 연속된 0의 갯수를 나타내는 리스트를 만들고, 그 중 가장 큰 값을 반환합니다.

 

1차로 업로드를 하면 3개의 테스트 케이스만 보여지고, 실제로는 제출을 해야 나머지 케이스에 대해서도 평가를 할 수 있다. 

 

페이지가 넘어가서 채점이 되는 구조라 다른 플랫폼과 다르다. 

 

반응형

'Algorithm > Codility' 카테고리의 다른 글

[Codility] CyclicRotation 파이썬 풀이  (0) 2024.01.23

댓글