[프로그래머스] Lv2. 이진 변환 반복하기

lemythe423·2023년 7월 3일
0
post-thumbnail

문제

풀이

def solution(s):
    x = s

    answer = [0, 0]
    while x != '1':
        c = 0
        for i in x:
            if int(i): c += 1

        answer[1] += len(x) - c
        answer[0] += 1

        x = str(bin(c)[2:])

    return answer

시간이 너무 오래 걸리는 게 있어서 수정한 코드

  • x 안에 있는 값을 비교할 때 문자열 -> 숫자로 변경하는 int()를 사용하지 않고 문자열 그대로('1') 비교
def solution(s):
    x = s

    ans = [0, 0]
    while x != '1':
        c = 0
        for i in x:
            if i == '1': c += 1

        ans[1] += len(x) - c
        ans[0] += 1
        x = str(bin(c)[2:])

    return ans

더 빨라졌지만 count() 함수를 사용한 게 제일 빨랐다

def solution(s):
    x = s

    ans = [0, 0]
    while x != '1':
        c = x.count('1')

        ans[1] += len(x) - c
        ans[0] += 1
        x = str(bin(c)[2:])

    return ans

profile
아무말이나하기

0개의 댓글