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:
Input: 2 Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
Related Topics:
Dynamic Programming, Bit Manipulation
Similar Questions:
All the numbers of power of 2 only have a single bit.
For each number between 2^k
and 2^(k+1)
, we can get them by adding 1, 2, 3, ..., 2^k - 1
to 2^k
.
And 1, 2, 3, ..., 2^k - 1
doesn't have bit overlap with 2^k
.
// OJ: https://leetcode.com/problems/counting-bits
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans(num + 1);
for (int i = 1; i <= num; i *= 2) {
ans[i] = 1;
for (int j = 1; j < i && i + j <= num; ++j) ans[i + j] = ans[i] + ans[j];
}
return ans;
}
};
i & -i
is the lowest bit of i
. Let dp[i]
be the number of bits of i
.
dp[i] = 1 + dp[i - (i & -i)]
// OJ: https://leetcode.com/problems/counting-bits/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans(num + 1);
for (int i = 1; i <= num; ++i) ans[i] = 1 + ans[i - (i & -i)];
return ans;
}
};
// OJ: https://leetcode.com/problems/counting-bits
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ans(num + 1, 0);
for (int i = 1; i <= num; ++i) ans[i] = ans[i / 2] + (i % 2);
return ans;
}
};