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].
要求O(n)时间
巧妙的利用了i&(i - 1), 这个本来是用来判断一个数是否是2的指数的快捷方法,比如8,二进制位1000, 那么8&(8-1)为0,只要为0就是2的指数, 那么我们现在来看一下0到15的数字和其对应的i&(i - 1)值:
i bin '1' i&(i-1)
0000 0
-----------------------
0001 1 0000
-----------------------
0010 1 0000
0011 2 0010
-----------------------
0100 1 0000
0101 2 0100
0110 2 0100
0111 3 0110
-----------------------
1000 1 0000
1001 2 1000
1010 2 1000
1011 3 1010
1100 2 1000
1101 3 1100
1110 3 1100
1111 4 1110
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res(num + 1, 0);
for (int i = 1; i <= num; ++i) {
res[i] = res[i & (i - 1)] + 1;
}
return res;
}
};