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:
Example 2:
Follow up:
To simplify explanations, the following list number from 0 to 15 in 4-bit format.
NOTE: The most right side is a lower bit(bit 0).
Then group numbers through the power of 2.
Group
And
Group
Group
Group
To count the bit quickly, that can refer to previous results and simply plus 1 to get the result of the current number.
For example:
Number 10 is in group (8), the bits can refer to number 2(10 - 8), so the bits is: 1 + 1 = 2
The concepts same as solution 1, the reference number is divided by the current number, then check whether the current number is odd or not, if so plus 1.
For example:
Number 7 can refer to the number 3(7 / 2 = 3.5, ignore the decimal point), the bits of number is 2 and the number is odd, so the bits of number would be 3(2 + 1).
In other words, the number 7 is 2 times 3 plus 1 that means the number 7 equals the bits of 3 left shift 1 bit then plus 1.
See the full solution.
leetcode
Medium
Bit Manipulation
Dynamic Programming