[Programmers] Level 2. 이진 변환 반복하기

Seo Seung Woo·2022년 9월 11일
0
post-thumbnail

Level 2. 이진 변환 반복하기


❔Thinking

  • 0,1로 이루어진 문자열에서 0을 제거하고 남은 1의 개수를 이진수로 변환하는 과정을 1이 될때까지 반복한다.
  • 이때, 변환 횟수와 제거한 0의 총 개수를 array에 담아 출력한다.

💻Solution

def solution(s):
    answer = []
    trans_cnt, zero_cnt = 0, 0
    x = s
    while x != '1':
        zero_cnt += x.count('0') # +0개수
        x = "1" * x.count('1') # 0 제거
        x = format(len(x), 'b') # x의 길이를 2진법으로 변환
        trans_cnt += 1 # 이진변환 +1
    answer = [trans_cnt, zero_cnt]
    return answer

🗝️keypoint

  • bin(값) / oct(값) / hex(값) => 값을 2진수/8진수/16진수로 변환 (접두어)
  • format(값, 'b/o/h') => 값을 2진수/8진수/16진수로 변환 (접두어 생략)
profile
Code for people

0개의 댓글