2024 상반기 취준 준비 코테

프로그래머스 이진 변환 반복하기

void_melody 2024. 3. 8. 10:26

https://school.programmers.co.kr/learn/courses/30/lessons/70129

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

python에서는 10진수 -> 2진수 변환하는 함수를 제공한다.

bin(n)을 쓰면 된다. 여기서 주의할 점은 앞에, '0b'가 붙어서 나온다. 그렇기에 slice를 해줘야한다.

# 나의 풀이
def solution(s):
    answer = []
    count = 0
    zero = 0
    while s != "1":
        t = ""
        for e in s:
            if e != '0':
                t += e
            else:
                zero += 1
        length = len(t)
        s = bin(length).replace("0b", "")
        count += 1
    answer.append(count)
    answer.append(zero)
    return answer
        
# 모범 답안
def solution(s):
    a, b = 0, 0
    while s != '1':
        a += 1
        num = s.count('1')
        b += len(s) - num
        s = bin(num)[2:]
    return [a, b]