Brian Kernighan 算法,a与a-1二进制相与,重复此操作,知道a为0,就可得二进制中1的个数
class Solution {
public int[] countBits(int n) {
int[] bit=new int [n+1];
for(int i=0;i<=n;i++){
bit[i]=countnumber(i);
}
return bit;
}
public int countnumber(int a){
int count=0;
while(a>0){
a&=(a-1);
count++;
}
return count;
}
}