【力扣】:比特位计数

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;
    }
}
相关推荐
来荔枝一大筐14 分钟前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
暴风鱼划水1 小时前
算法题(Python)数组篇 | 6.区间和
python·算法·数组·区间和
zl_vslam1 小时前
SLAM中的非线性优-3D图优化之轴角在Opencv-PNP中的应用(一)
前端·人工智能·算法·计算机视觉·slam se2 非线性优化
是苏浙1 小时前
零基础入门C语言之C语言实现数据结构之顺序表应用
c语言·数据结构·算法
前端架构师-老李1 小时前
进入新岗位的第一课——潜龙勿用
职场和发展
lkbhua莱克瓦242 小时前
Java基础——常用算法3
java·数据结构·笔记·算法·github·排序算法·学习方法
小白程序员成长日记2 小时前
2025.11.07 力扣每日一题
数据结构·算法·leetcode
·白小白2 小时前
力扣(LeetCode) ——209. 长度最小的子数组(C++)
c++·算法·leetcode
小猪咪piggy2 小时前
【算法】day16 动态规划
算法·动态规划
ohnoooo92 小时前
251106 算法
数据结构·c++·算法