想到了兩種解法:
(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