想到了两种解法:
(1)参照的是10进制数转换为2进制数的计算过程,代码如下:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> counts;
for(int i=0; i<=num; i++)
{
int count=0;
int temp=i;
do{
count += temp%2;
temp /= 2;
}while(temp!=0);
counts.push_back(count);
}
return counts;
}
};
time: 148ms
(2)移位,判断最后那个bit是0还是1,代码如下:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> counts;
for(int i=0; i<=num; i++)
{
int count=0;
int temp = i;
for(int j=1;j<8*sizeof(int);j++)
{
count += (0x01 & temp);
temp = temp >> 1;
}
counts.push_back(count);
}
return counts;
}
};
time: 152ms