各位朋友们,大家好啊,今天此题我用的方法比较好理解,但时间复杂度比较高如果大家觉得可以的话,不妨给个免费的赞吧,谢谢了^ _ ^
1.题目要求如图所示:
2.做题步骤:
1.先计算总共多少个数:
c
int count = 0;
int number = 0;
while(number <= n)
{
count++;
number++;
}
2.然后再用malloc函数:
c
int* number_t = (int*)malloc(sizeof(int) * count);
3.再采用双层while循环,再利按位与操作符和右移操作符来求每个数中1的个数:
c
int k = count;
number = 0;
count = 0;
int f = 0;
while(number <= n)
{
int numbers = number;
count = 0;
while(numbers)
{
if(numbers & 1 == 1)
{
count++;
}
numbers = numbers >> 1;
}
printf("%d ",count);
number_t[f] = count;
f++;
number++;
}
全部代码如图所示:
c
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* countBits(int n, int* returnSize) {
int count = 0;
int number = 0;
while(number <= n)
{
count++;
number++;
}
int* number_t = (int*)malloc(sizeof(int) * count);
int k = count;
number = 0;
count = 0;
int f = 0;
while(number <= n)
{
int numbers = number;
count = 0;
while(numbers)
{
if(numbers & 1 == 1)
{
count++;
}
numbers = numbers >> 1;
}
printf("%d ",count);
number_t[f] = count;
f++;
number++;
}
*returnSize = k;
return number_t;
}
好了,这就是我全部的代码,大家如果觉得好的话,请给个免费的赞吧,谢谢了^ _ ^