![]() |
VOOZH | about |
Given an integer n, return an array containing the number of set bits (1s) in the binary representation of every integer in the range [0, n].
Examples :
Input: n = 3
Output: [0, 1, 1, 2]
Explanation: The numbers from 0 to 3 have 0, 1, 1, and 2 set bits respectively.
Input: n = 7
Output: [0, 1, 1, 2, 1, 2, 2, 3]
Explanation: The numbers from 0 to 7 have 0, 1, 1, 2, 1, 2, 2, and 3 set bits respectively.
Table of Content
The idea is to iterate through all numbers from
0tonand count the set bits in each number individually by checking every bit position. Store the count obtained for each number in the result array.
[0, 1, 1, 2, 1, 2, 2, 3]
The idea is to use the count of set bits of a smaller number to compute the count for a larger number. For any number
i, the count of set bits equals the count of set bits ini >> 1plus1if the least significant bit ofiis set. Using this relation, we can build the answer for all numbers from0tonin a bottom-up manner.
Let us understand with example:
Input: n = 7
[0, 1, 1, 2, 1, 2, 2, 3]