LeetCode 338.比特位计数

各位朋友们,大家好啊,今天此题我用的方法比较好理解,但时间复杂度比较高如果大家觉得可以的话,不妨给个免费的赞吧,谢谢了^ _ ^

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;   
}

好了,这就是我全部的代码,大家如果觉得好的话,请给个免费的赞吧,谢谢了^ _ ^

相关推荐
IronMurphy1 小时前
【算法四十三】279. 完全平方数
算法
墨染天姬1 小时前
【AI】Hermes的GEPA算法
人工智能·算法
papership1 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826521 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
Beginner x_u2 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
_深海凉_5 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
踩坑记录6 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎6 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰6 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx6 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先