Mini Puzzle Game Four Python

Given a negative integer. For each numeric number in the range 0 ≤ i ≤ num, count the number of 1s in the number of binary digits and return them as an array.

class Solution:
    def countBits(self, num: int) -> List[int]:
        dec = num
        nums = []
        for i in range(dec+1):
            bino = bin(i)[2:]
            nb = 0
            for _ in bino:
                if _ == "1":
                    nb = nb + 1
            nums.append(nb)
        return nums

Below is Leecode’s official response

class Solution:
    def countBits(self, num: int) -> List[int]:
        bits = [0]
        for i in range(1, num + 1):
            bits.append(bits[i >> 1] + (i & 1))
        return bits

surprising!

Leave a Comment