codibility - BinaryGap

이슬비·2025년 6월 2일
0

Coding Test

목록 보기
7/16

문제

  • 이진수에서 1 간의 거리를 binary gap이라고 정의
  • binary gap이 여러 개 나타날 때 max binary gap 구하기

내가 작성한 코드

def solution(N):
    # Implement your solution here
    def get_binary(N):
        binary = []
        while (N // 2) != 1:
            binary.append(N % 2)
            N = N // 2
        if N == 2:
            binary.extend([0, 1])
        else:
            binary.extend([1, 1])
        binary = binary[::-1]
        return binary

    binary_value = get_binary(N)
    max_gap = 0
    cnt = 0
    for b in binary_value:
        if b == 1:
            if cnt != 0 and max_gap < cnt:
                max_gap = cnt
                cnt = 0
        else:
            cnt += 1
    return max_gap
  • 옥에 티가 아닌 티에 티
    • 이진법 직접 구현 ... 하드하드코딩 ㅋ
    • cnt들의 list를 만들고 거기서 max 값을 골라도 됐을듯

GPT 피드백

def solution(N):
    binary = bin(N)[2:]  # '0b' 제거
    max_gap = 0
    current_gap = 0
    found_one = False

    for bit in binary:
        if bit == '1':
            if found_one:
                max_gap = max(max_gap, current_gap)
            found_one = True
            current_gap = 0
        elif found_one:
            current_gap += 1

    return max_gap
  • bin 함수를 통해 내가 직접 구현하지 않아도 이진수를 만들 수 있다 ...
  • max 함수를 쓰도록 하자 ...
profile
정말 알아?

0개의 댓글