思路为:编写一个计算二进制位的函数,然后从0~n依次遍历,得到返回的链表。
Brian Kernighan 算法的原理是:对于任意整数 x,令 x=x & (x−1),该运算将 x 的二进制表示的最后一个 1 变成 0。因此,对 x 重复该操作,直到 x变成 0。
class Solution {
public int[] countBits(int n) {
int[] arr = new int[n+1];
for(int i=0; i<=n; i++){
arr[i] = countOne(i);
}
return arr;
}
public int countOne(int x){
int res = 0;
while(x>0){
x=x&(x-1);
res++;
}
return res;
}
}