题目内容如下:
解法一 Your runtime beats <u>2.96%</u> of cppsubmissions.
class Solution {
public:
vector<int> countBits(int num) {
vector<int> countBits;
for(int i = 0; i<=num; i++){
int count=0;
int temp1=i;
while(temp1>0){
//将这个数与1进行异或,也就是将其二进制的最低位与1进行异或,
//因为1^1=0;0^1=0,
//所以如果异或结果变小了,那么最低位就是1,如果异或结果变大了,那么最低位就是0.
int res=temp1^1;
if(temp1>res)
count++;
//然后将这个数右移一位,再次进行循环异或
temp1>>=1;
}
countBits.push_back(count);
}
return countBits;
}
};
解法二 Your runtime beats <u>19.25%</u> of cppsubmissions.
思路:将所有数都写出来,发现这个数组的规律是
{0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4...}
可看到如果分别数到第0,2,4,8,16个的时候,每一组都是在上一组的数值上加1,所以这道题的解法也就出来了
class Solution{
public:
vector<int> countBits(int num){
vector<result> res;
ans.push_back(0);//奠定第一个值
if(num == 0)
return and;
for(int i = 1; j=0; i<=num;i++){
if(i>=pow(2,j+1))
j++;
ans.push_back(ans.at(i-pow(2,j))+1);
}
return ans;
}
};
解法三:Your runtime beats <u>3.45%</u> of cppsubmissions.
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
res.push_back(0);//奠定第一个值
if(num == 0)
return res;
for(int i = 1, j=0; i<=num;i++){
res.push_back(res.at(i/2)+i%2);
}
return res;
}
};
解法四:Your runtime beats <u>77.64%</u> of cppsubmissions.
思路:受闺蜜启发,感觉这个规律很牛逼。
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
res.push_back(0);
if(num == 0)
return res;
for(int i = 1; i<=num;i++){
int temp = i&(i-1);
res.push_back(res.at(temp)+1);
}
return res;
}
};
解法五:Your runtime beats <u>98.12%</u> of cppsubmissions.
思路:将res.at换成res[],速度稍有提升
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
res.push_back(0);
if(num == 0)
return res;
for(int i = 1; i<=num;i++){
int temp = i&(i-1);
res.push_back(res[temp]+1);
}
return res;
}
};
遇到的问题:比如说最后一种解法,第一次看details,时间是98.12%,第二次再看details,时间就是50%多了。