[Programmers] 70129 이진변환 반복하기 python

프로그래머스 월간코드 챌린지 1번

level 2

풀이

읽히는 대로 코드를 짤 수 있었던 문제.
딱히 꼬지 않았다고 생각했다.
그런데, 첫번째 풀이에서 테스트케이스 마지막 3개에서 시간초과가 났다.
연산이 많았던 것 같음.
그래서 내장함수를 사용해서 풀었다.


첫번째 풀이.
테케에서 시간초과 남

def remove_zero(s):
    global zero_count
    s = list(s)
    while '0' in s:
        zero_count += 1
        s.remove('0')
    return s


def make_binary(num):
    if num > 0:
        q = num // 2
        r = str(num % 2)
        return make_binary(q)+r
    return ""


zero_count = 0


def solution(s):
    round = 0
    while int(s) > 1:
        round += 1
        s_without_zero = ''.join(remove_zero(s))
        new_num = len(s_without_zero)
        s = make_binary(new_num)
    answer = [round, zero_count]
    return answer

통과 풀이

def solution(s):
    round = 0
    zero_count = 0
    while s != "1":
        round += 1
        zero_count += s.count("0")
        s = s.replace("0","")
        new_num = len(s)
        s = bin(new_num)[2:]
    answer = [round, zero_count]
    return answer

좋은 웹페이지 즐겨찾기