[Leet Code] Countings bits

Matthew Boyd
1 min readDec 17, 2020

Leetcode: https://leetcode.com/problems/counting-bits/

Problem:

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

Example 1:

Input: 2
Output: [0,1,1]

Example 2:

Input: 5
Output: [0,1,1,2,1,2]

Solution:

class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
answer = []
for i in range(num+1):
binAnswer = list((format(i, "b")))
answer.append(binAnswer.count("1"))
return answer

Explanation:

First we create an answer array, as that’s what we have to return. Then we iterate from 0->num+1 (because of index starting point) and ((format(i,"b")) will generate the binary representation of your iterating number. Then we want to turn this into a list to make use of lists methods, such as count, which we do in the next line whereby we count the number of 1s that are displayed. Then we append it to the answer array. Then finally, we return the answer array.

--

--