Counting Bits II

This is an extension to the previous problem counting the number of set bits or 1's present in a number.

Introduction

This is an extension of the previous counting set bits problem.

Problem Statement

Write a program to return an array of number of 1’s in the binary representation of every number in the range [0, n].

Input: n = 6

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

Explanation: 
0 --> 0
1 --> 1
2 --> 1
3 --> 2
4 --> 1
5 --> 2
6 --> 2

Solution

This is a faster execution as we use Brian Kernighan’s algorithm.

In this approach, we count only the set bits. So,

If a number has 2 set bits, then the ...