2023-06-16 이진 변환

Summary

이진 변환 함수 bin 의 이름이 기억이 나지 않았음. 실제로 이렇게 특정 모듈의 이름이 기억나지 않을 때에는 가능하면 실제로 구현하여 사용하는 방법 밖에는 없을 것이다..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def solution(s):
    """
    10 -> 5 -> 2 -> 1 -> 0 
          0    1    0    1
    """
    def decimalToBinary(decimal):
        res = ''
        while decimal != 0:
            res = str(decimal % 2) + res
            decimal //= 2
        return res
    
    ans = [0, 0]
    while s != '1':
        zeroCount = s.count('0')
        ans[1] += zeroCount
        s = '1' * (len(s) - zeroCount)
        s = decimalToBinary(len(s))
        ans[0] += 1    

    return ans

comments powered by Disqus