Leetcode-338. Counting Bits

Original link: https://leetcode.com/problems/counting-bits/

This question gives a number and requires a list returned.
Each element in the list represents how many “1” they have in their binary representation.

Let me list several numbers and their corresponding binary respresentation:

Number Binary Representation
0 00000000
1 00000001
2 00000010
3 00000011
4 00000100
5 00000101
6 00000110
7 00000111
8 00001000
9 00001001
10 00001010

We can find two things,
1)
1, 2, 4, 8 … have only single 1
3, 6 … have two 1.
2)
For each odd n, the last bit should be 1 and all other bits should be equal as the previous number n-1

As we have two rules, we can cover all numbers.

Code:

class Solution:
    def countBits(self, num: int) -> List[int]:
        
        ans = [-1 for i in range(num+1)]
        ans[0] = 0
        
        for pointer in range(1, num+1):
            if ans[pointer] == -1:
                ans[pointer] = ans[pointer-1] + 1
                temp = pointer * 2
                while temp <= num:
                    ans[temp] = ans[pointer]
                    temp *= 2
        
        return ans

你可能感兴趣的:(Leetcode,Leetcode)