您的位置:首页 > 其它

Counting Bits

2016-05-13 17:04 190 查看
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and
return them as an array.

Example:

For
num = 5
you should return
[0,1,1,2,1,2]
.

Follow up:

It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
Space complexity should be O(n).
Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

题目:计算从0到num之间所有数各自二进制中的1的个数
思路:三种方法
(1)寻找规律,使用DP
static public int[] countBits(int num) {
int[] result = new int[num+1];
result[0]=0;
int offset=1;
for(int i=1;i<num+1;i++){
if(i==(1<<offset)){
offset<<=1;
}
result[i]=result[i-offset]+1;
}
return result;
}
(2)巧妙利用bit i&(i - 1),这个本来是用来判断一个数是否是2的指数的快捷方法
public static int[] countBits2(int num) {
int[] result = new int[num+1];
for(int i=1;i<num+1;i++){
result[i]=result[i&(i-1)]+1;
}
return result;
}
(3)利用奇偶性,奇数个数等于奇数除2的个数加+1,偶数个数等于偶数除2的个数;

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