```
public int[] countBits(int num) {
int[] result = new int[num+1];
int power, nextPower, p, i;
result[0] = 0;
power = nextPower = 1;
p = 0; /* Start with pow(2,0) */
i = 1; /* Fill array from i = 1 */
while( i <= num ) {
if( i < nextPower ) {
result[i] = result[i-power] + 1;
i++;
}
else {
power = nextPower;
nextPower <<= 1;
}
}
return result;
}
```