LeetCode 338
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].
Solution:
因为是递增,所以可以找res[i] = res[i & (i-1)] + 1的规律
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res(num+1, 0);
for (int i = 1; i < num+1; i++) {
res[i] = res[i & (i-1)] + 1;
}
return res;
}
};
改进:
用bitset,count()函数
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res(num+1, 0);
for (int i = 1; i < num+1; i++) {
res[i] = bitset<32>(i).count();
}
return res;
}
};