题目:给定一个非负整数 n ,请计算 0 到 n 之间的每个数字的二进制表示中 1 的个数,并输出一个数组。
示例 1:
输入: n = 2
输出: [0,1,1]
解释: 0 --> 0
1 --> 1
2 --> 10
示例 2:
输入: n = 5
输出: [0,1,1,2,1,2]
解释: 0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
解法1:1比特数法,对于一个数x,令x=x&(x-1)可以将x的二进制表示中的最后一位1转变为0,而当将x转为0的次数,即为数x的二进制中的1的个数
class Solution {
public int[] countBits(int n) {
int[] res = new int[n+1];
for(int i = 0; i <= n; i++){
res[i] = countOneBit(i);
}
return res;
}
public int countOneBit(int x){
int count = 0;
while(x != 0){
count++;
x = x & (x-1);
}
return count;
}
}
解法2:对于一个数x。考虑其二进制,可以发现当x为偶数时,x = (x/2) << 1; 当x为奇数时,x = (x/2) << 1之后再在末尾补上1个1。
class Solution {
public int[] countBits(int n) {
int[] res = new int[n+1];
for(int i = 0; i <=n; i++){
res[i] = res[i>>1] + (i&1); //二进制数,末位为0对应十进制数为偶数,否则对于十进制数为奇数
}
return res;
}
}