我的解题思路有两种。第一种是利用Integer类的static int bitCount(int i) 函数。第二种是利用转台转移方程:P(x)=P(x/2)+(xmod2)
class Solution {
// public int[] countBits(int num) {
// int[] res = new int[num + 1];
// for (int i = 0; i < num + 1; i++) {
// res[i] = Integer.bitCount(i);
// }
// return res;
// }
public int[] countBits(int num) {
int[] res = new int[num + 1];
res[0] = 0;
for (int i = 1; i < num + 1; i++) {
res[i] = res[i >> 1] + (i & 1);
}
return res;
}
}