【力扣】:比特位计数

1.去掉二进制中最左边的1,n&(n-1),如果一次操作以后,就是0,那么这个数是2的倍数。进行几次操作,,变为0,那么就有几个1.

2.拿到最左边的1,n&-n

3.将x位改为0,~(1<<x)&n

4,x位改为1,1<<x|n.

解法一:

复制代码
class Solution {
public:
    vector<int> countBits(int n) {
        vector<int> bits(n + 1);
        for (int i = 0; i <= n; i++) {
                int ones = 0;
                while (x > 0) {
                x &= (x - 1);
                ones++;
            }
            bits[i]=ones;
        }
        return bits;
    }
};

解法2:

动态规划

复制代码
class Solution {
    public int[] countBits(int n) {
        int[] bits = new int[n + 1];
        int highBit = 0;
        for (int i = 1; i <= n; i++) {
            if ((i & (i - 1)) == 0) {
                highBit = i;
            }
            bits[i] = bits[i - highBit] + 1;
        }
        return bits;
    }
}
相关推荐
思成Codes18 分钟前
ACM训练:接雨水3.0——动态接雨水
数据结构·算法
alphaTao18 分钟前
LeetCode 每日一题 2026/1/12-2026/1/18
python·算法·leetcode
sin_hielo20 分钟前
leetcode 2943
数据结构·算法·leetcode
Snow_day.1 小时前
有关平衡树
数据结构·算法·贪心算法·动态规划·图论
Hcoco_me1 小时前
大模型面试题75:讲解一下GRPO的数据回放
人工智能·深度学习·算法·机器学习·vllm
Xの哲學1 小时前
Linux设备驱动模型深度解剖: 从设计哲学到实战演练
linux·服务器·网络·算法·边缘计算
明洞日记2 小时前
【CUDA手册002】CUDA 基础执行模型:写出第一个正确的 Kernel
c++·图像处理·算法·ai·图形渲染·gpu·cuda
企业对冲系统官2 小时前
基差风险管理系统集成说明与接口规范
大数据·运维·python·算法·区块链·github
程序员-King.2 小时前
day134—快慢指针—环形链表(LeetCode-141)
算法·leetcode·链表·快慢指针
Swift社区2 小时前
LeetCode 376 摆动序列
算法·leetcode·职场和发展