릿코드 위클리에 나온 문제라던데 아는 분이 물어봐서 올림


class Solution:

    def makeTheIntegerZero(self, num1: int, num2: int) -> int:

        cnt = 0

        while True:

            cnt, num1 = cnt + 1, num1 - num2

            if num1 <= 0 or cnt > 32: return -1

            bits, num = 0, num1

            while num: num, bits = num & (num - 1), bits + 1

            if bits <= cnt <= num1: return cnt


사용된 알고리즘은 비트를 계산하는 Kernighan's algorithm. 의외로 자주 쓰인다.

위에서는 pythonic하게 한 줄로 처리했음


def countBits(n: int):

    count = 0

    while n > 0:

    n = n & (n-1) # Key idea. 최하위 비트 제거

    count = count + 1

    return count