Ninja was given an integer ‘N’. For each number from ‘0’ to ‘N’, he must print the number of set bits present in its binary representation.
For example:
The binary representation of ‘5’ is 101. Therefore the number of set bits is 2.
First-line contains ‘T’, denoting the number of Test cases.
For each Test case:
The first line contains an integer, ‘N’, denoting the number until you have to print the number of set bits in its binary representation.
Output Format-
For each test case, you have to print ‘N + 1’ space-separated integers, denoting the number of set bits in the binary representation.
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 10
0 <= ‘N’ <= 10^5
Note- Sum of ‘N’ over all test cases does not exceed 10^5.
Time Limit: 1 sec
2
3
5
0 1 1 2
0 1 1 2 1 2
For test case 1:
The binary representation of 0 is ‘0’. Hence the total set bit is 0.
The binary representation of 1 is ‘1’. Hence the total set bit is 1.
The binary representation of 2 is ‘10’. Hence the total set bit is 1.
The binary representation of 3 is ‘11’. Hence the total set bit is 2.
2
0
2
0
0 1 1
Check every bit of each number.
Approach: For each number, we will check all its bits. If the bit is set, we increase the counter. Else, check the next bit.
Algorithm:
O(N * log(N)), where N is the given number.
For each number, we are checking all its bits. Hence the overall complexity is O(N * log(N)).
O(1).
We are creating a single variable. Hence the overall complexity is O(1).