动态规划解法
import java.util.Arrays;
//动态规划,找出递推的规律
public class Solution2 {
public static void main(String[] args) {
int[] ans = new Solution2().countBits(5);
System.out.println(Arrays.toString(ans));
}
public int[] countBits(int num) {
int[] arr = new int[num + 1];
int b = 1;
int i = 0;
//达成条件说明arr[num]已经被计算了
while(b <= num){
//内循环下标大b的位置1的数量增加一个
while(i < b && i + b <= num){
arr[i + b] = arr[i] + 1;
i++;
}
b <<= 1;//b翻倍
i = 0;//重置i
}
return arr;
}
}
不同颜色代表不同内循环轮次
暴力遍历法
import java.util.Arrays;
/*
暴力遍历,对每个数字进行计算
*/
public class Solution1 {
public static void main(String[] args) {
Solution1 s = new Solution1();
int[] ans = s.countBits(5);
System.out.println(Arrays.toString(ans));
// int i = s.countOnes(7);
// System.out.println(i);
}
public int[] countBits(int num) {
int[] ans = new int[num + 1];
for (int i = 0; i < num + 1; i++) {
ans[i] = countOnes(i);
}
return ans;
}
public int countOnes(int num){
int count = 0;
int mask = 1;
for (int i = 0; i < 32; i++) {
if((num & mask) != 0)
count++;
mask <<= 1;
}
return count;
}
}