끄적끄적

Codility Lesson1 - Iterations 본문

Codility Lessons

Codility Lesson1 - Iterations

kminx 2023. 9. 12. 11:22

Codility Lesson1 - 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].

-> 숫자를 이진수로 변경후 1과 1사이의 0의 값이 max 인 값 찾기

    ex) 10000010001  -> 5

 

 

정답

def solution(N):
    # Implement your solution here  
    bina=bin(N)[2:]
    idx=[]

    for i in bina:
        idx.append(i)

    length=len(idx)
    ans=[]
    for i in range(1,length):
        if (idx[i-1]=='1') and (idx[i]=='0'):
            ans.append(i)
        elif (idx[i-1]=='0') and (idx[i]=='1') and((len(ans))%2==1):
            ans.append(i)
    maxi=[]
    if (len(ans))%2==0:
        for i in range(0,len(ans),2):
            a=ans[i+1]-ans[i]
            maxi.append(a)
    else:
        for i in range(0,len(ans)-1,2):
            a=ans[i+1]-ans[i]
            maxi.append(a)
    
    if maxi:
        result=max(maxi)
    else:
        result=0

    return result

 

결과

'Codility Lessons' 카테고리의 다른 글

Cobility Lesson3 - TapeEquilibrium  (0) 2023.09.14
Cobility Lesson3 - PermMissingElem  (0) 2023.09.13
Codility Lesson3 - FrogJmp  (0) 2023.09.13
Codility Lesson2 - OddOccurrencesInArray  (0) 2023.09.13
Codility Lesson2 - CyclicRotation  (0) 2023.09.13