class Solution {
public int[] countBits(int n) {
int[] result=new int[n+1];
for(int i=0;i<=n;++i){
result[i]=oneCount(i);
}
return result;
}
public int oneCount(int x){
int count=0;
while(x!=0){
x=x&(x-1);
++count;
}
return count;
}
}
动态规划:
class Solution {
public int[] countBits(int n) {
int[] result=new int[n+1];
for(int i=1;i<=n;++i){
result[i]=result[i&(i-1)]+1;
}
return result;
}
}