< Previous
Next >
Given an integer num
, return an array of the number of 1
's in the binary representation of every number in the range [0, num]
.
Example 1:
Input: num = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
Example 2:
Input: num = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
Constraints:
Follow up:
- It is very easy to come up with a solution with run time
O(32n)
. Can you do it in linear time O(n)
and possibly in a single pass?
- Could you solve it in
O(n)
space complexity?
- Can you do it without using any built-in function (i.e., like
__builtin_popcount
in C++)?
[Bit Manipulation]
[Dynamic Programming]
Similar Questions
- Number of 1 Bits (Easy)
Hints
Hint 1
You should make use of what you have produced already.
Hint 2
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
Hint 3
Or does the odd/even status of the number help you in calculating the number of 1s?