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.
Example:
For num = 5 you should return [0,1,1,2,1,2].
Follow up:
1.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?
2.Space complexity should be O(n).
3.Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.
代码如下:
1.一种投机取巧的方法(本题不支持)
#include <bitset>
class Solution {
public:
vector<int> countBits(int num) {
vector<int> num(num + 1, 0);
for (int i = 0; i < num + 1; i++) {
num[i] = bitset<32>(i).count();
}
return num;
}
};
2.正确解法
class Solution {
public:
vector<int> countBits(int num) {
vector<int> dp(num + 1, 0);
for (int i = 1; i < num + 1; i++) {
dp[i] = dp[i & (i - 1)] + 1;
}
return dp;
}
};
解题思路:
经观察可以发现,i 的二进制表示中1的个数恰好等于i &(i-1)所得数的二进制1的个数加1:
i bin '1' i&(i-1)
0 0000 0
-----------------------
1 0001 1 0000
-----------------------
2 0010 1 0000
3 0011 2 0010
-----------------------
4 0100 1 0000
5 0101 2 0100
6 0110 2 0100
7 0111 3 0110
-----------------------
8 1000 1 0000
9 1001 2 1000
10 1010 2 1000
11 1011 3 1010
12 1100 2 1000
13 1101 3 1100
14 1110 3 1100
15 1111 4 1110
且 i &(i - 1)通常可以用来判断一个数是否为2的指数,只要结果为0,就是2的指数。