https://app.codility.com/programmers/lessons/1-iterations/binary_gap/

 

BinaryGap coding task - Learn to Code - Codility

Find longest sequence of zeros in binary representation of an integer.

app.codility.com

 

  • 양의 정수 N이 주어질 때
  • 2진수로 표현한 후, 가장 큰 binary gap을 구해준다.
  • binary gap : 1과 1사이에 있는 0들의 개수
  • ex. 10000010001 -> binary gap = 5
  • ex. 100000 -> no binary gap 

 

def solution(N):
    # 2진수 변환 앞의 2자리 버리기
    binaryNum = bin(N)[2:]
    gap = 0
    maxGap = 0
    flag = False
    for i in range(len(binaryNum)):
        if binaryNum[i] == '1':  # 첫번째 값
            if flag:  # 두번째 값
                if maxGap < gap:
                    maxGap = gap
                gap = 0
            else:
                flag = True

        elif flag:
            gap = gap + 1

    return maxGap

+ Recent posts