Loading...

LCR003-比特位计数

在这里插入图片描述

求解代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
public int[] countBits(int n) {
        int[] bits = new int[n+1];

        for(int i=0;i<=n;i++){
            bits[i]=oneBits(i);
        }
        return bits;
    }

    private int oneBits(int n){
        int count = 0;
        while(n>0){
            n&=(n-1);
            count++;
        }
        return count;
    }

小贴士

核心就是用 n & (n-1) 消去最右侧 1的技巧统计 1 的个数。

最后更新于 2026-04-05 17:35:33
Code Road Record