LeetCode 338.Counting Bits 解题报告
题目描述
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。
示例
For num = 5 you should return [0,1,1,2,1,2].
限制条件
- 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.
解题思路
观察以下 num<8 的结果:
num | 1的个数 |
---|---|
0 | 0 |
1 | 1 |
2 - 3 | 1 2(1+1, 2的个数+1的个数) |
4 - 7 | 1 2(1+1, 4的个数+1的个数) 2(1+1, 4的个数+2的个数) 3(1+2, 4的个数+3的个数) |
观察上表可以得出以下规律:
1.对于
2n
,二进制表示中只在第n个bit上是1。
2.对于
m=2n+k,(k<2n)
,
m
的二进制表示中1的个数为1(
3.规律2的递推前提是0和1的情况,所以从
代码
class Solution {
public:
vector<int> countBits(int num) {
vector<int> veci;
if (num >= 0) {
veci.push_back(0);
}
if (num >= 1) {
veci.push_back(1);
}
for (int i = 2; i <= num;) {
// the case of 2^n
veci.push_back(1);
for (int j = 1; j < i && j <= num - i; j++) {
// the case of m = 2^n + k, k < 2^n
veci.push_back(1 + veci[j]);
}
i += i;
}
return veci;
}
};