↓ Skip to main content
  1. Science/
  2. Computer/

0338.Counting Bits

Solution

from typing import List

class Solution:
    def countBits(self, n: int) -> List[int]:
        return [i.bit_count() for i in range(n + 1)]

if __name__ == "__main__":
    sol = Solution()
    print(sol.countBits(5)) # [0,1,1,2,1,2]

Solution 2

from typing import List

class Solution:
    def countBits(self, n: int) -> List[int]:
        ans = [0] * (n + 1)
        for i in range(1, n + 1):
            ans[i] = ans[i & (i - 1)] + 1
        return ans

if __name__ == "__main__":
    sol = Solution()
    print(sol.countBits(5)) # [0,1,1,2,1,2]