您的位置:首页 > 其它

LeetCode---Counting Bits解题分析

2016-06-04 15:09 246 查看
题意描述:给定一个非负整数num,则返回区间[0,num]中每个数字对应的二进制中1的个数。比如“num=5”,返回[0, 1, 1, 2, 1, 2]

解题思路一:这里借鉴“Number of 1 Bits”的解法,一个函数实现计算数字的二进制形式中1的个数,然后在另一个函数中调用进而求出区间内每个数字的二进制形式中1的个数

public int NumbersOf1Bits(int n) {
int count = 0;
while(n != 0){
count++;
n = n & (n-1);//把一个数字与该数字减去1后再与,就会将二进制形式的最后一位1转化为0,有多少个1进行多少次操作即可
}
return count;
}
public int[] countBits(int num) {
int[] result = new int[num+1];
for(int i=0; i<result.length; i++)
result[i] = NumbersOf1Bits(i);
return result;
}
解题思路二:解法一的思路对于数字K并没有运用数字K之前的结果进行求解,而是每个数字都单独计算。而对于2^N的数,末尾N-1位的重复规律,正好等于前N-1个数的重复规律,利用这一特点只需要加1即可

int[] result = new int[num+1];
result[0] = 0;
int base = 1;
while(base <= num){
int next = base * 2;
for(int i=base; i<next && i<= num; i++)
result[i] = result[i-base]+1;
base = next;
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: