给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
示例 1:
输入: 2
输出: [0,1,1]
示例 2:
输入: 5
输出:
[0,1,1,2,1,2]
思路一:循环num将每个数转为二进制的字符串,然后再遍历字符串中1的个数,将个数存到数组中。
代码:
public static void main(String[] args) {
int num = 100;
System.out.println(Arrays.toString(countBits(num)));
}
public static int[] countBits(int num) {
int[] arr = new int[num + 1];//因为要加0,所以长度要加1
int count = 0;//用于计算二进制中1的个数
for(int i = 0;i <= num;i++){
String s = Integer.toBinaryString(i);//10进制转二进制
//遍历二进制字符串中1的个数
for(int j = 0;j < s.length();j++){
if(s.charAt(j) == '1'){
count++;
}
}
arr[i] = count;
count = 0;
}
return arr;
}
思路二:“ & ”的应用;[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]这是输入15时输出的结果,发现奇数位与比他小一的偶数位相差一,我只要求出前面的那个,后面的加1就好了。是二的倍数位肯定是1,“&”运算过是等于arr[0] + 1,其余的偶数位,等于他前两位的值加1.
参考:https://www.jianshu.com/p/c45abee3fee5
代码:
public static void main(String[] args) {
int num = 15;
System.out.println(Arrays.toString(countBits(num)));
}
public static int[] countBits(int num) {
int[] arr = new int[num + 1];
for(int i = 1;i <= num;i++){
arr[i] = arr[i & (i - 1)] + 1;
}
return arr;
}