问题
给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。
例子

思路
-
方法1
O(nlogn)
先算一个数,然后外面for循环 -
方法2
O(n)
i >> 1会把最低位去掉,因此i >> 1 也是比i小的,同样也是在前面的数组里算过。当 i 的最低位是0,i>>1是比i小的最大的偶数,则 i 中1的个数和i >> 1中1的个数相同;当i的最低位是1,i>>1是偶数i 中1的个数是 i >> 1中1的个数再加1
代码
//方法1
class Solution {
public int[] countBits(int num) {
int[] res = new int[num+1];
for(int i=1; i<=num; i++) {
int j=i,count=0;
while(j>0) {
if((j&1)==1) count++;
j>>>=1;
}
res[i]=count;
}
return res;
}
}
//方法2
class Solution {
public int[] countBits(int num) {
int[] res = new int[num+1];
for(int i=1; i<=num; i++) {
res[i]=res[i>>1]+(i&1);
}
return res;
}
}

904

被折叠的 条评论
为什么被折叠?



