leetcode 338. 比特位计数

文章目录

338. 比特位计数

链接

暴力算法

java 复制代码
class Solution {

    private int count(int n) {
        int res = 0;
        if (n == 0) {
            return 0;
        }
        for (int i = 0; i < 32; i++) {
            res += ((n >> i) & 1);
        }
        return res;
    }

    public int[] countBits(int n) {
        int[] ans = new int[n+1];
        for (int i = 0; i <= n; i++) {
            ans[i] = count(i);
        }
        return ans;
    }
}

存储已经计算的值

java 复制代码
class Solution {

    
    public int[] countBits(int n) {
        int[] ans = new int[n+1];
        for (int i = 0; i <= n; i++) {
            ans[i] = ans[i >> 1] + (i & 1);
        }
        return ans;
    }
}
相关推荐
阿Y加油吧2 小时前
LeetCode 中等难度 | 回溯法进阶题解:单词搜索 & 分割回文串
算法·leetcode·职场和发展
QH_ShareHub2 小时前
反正态分布算法
算法
float_com2 小时前
LeetCode 27. 移除元素
leetcode
王老师青少年编程2 小时前
csp信奥赛c++中的递归和递推研究
c++·算法·递归·递推·csp·信奥赛
Bczheng12 小时前
五.serialize.h中的CDataStream类
算法·哈希算法
小O的算法实验室2 小时前
2025年SEVC,考虑组件共享的装配混合流水车间批量流调度的多策略自适应差分进化算法,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
汀、人工智能2 小时前
[特殊字符] 第36课:柱状图最大矩形
数据结构·算法·数据库架构·图论·bfs·柱状图最大矩形
List<String> error_P3 小时前
蓝桥杯最后冲刺(三)
算法
样例过了就是过了3 小时前
LeetCode热题100 跳跃游戏
c++·算法·leetcode·贪心算法·动态规划
无限进步_3 小时前
【C++&string】寻找字符串中第一个唯一字符:两种经典解法详解
开发语言·c++·git·算法·github·哈希算法·visual studio