您的位置:首页 > 其它

LeetCode 338 Counting Bits

2016-04-10 00:35 381 查看
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.

Hint:

You should make use of what you have produced already.
Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
Or does the odd/even status of the number help you in calculating the number of 1s?

题目分析:

对于一个给定的数字num, 给出[0,num]区间内的每个数的二进制表示所含的1的个数,用一个数组输出结果。
可以参考:n&(n-1)妙用
public int[] countBits(int num) {
int[] nums = new int[ num+1];
nums[0] =0;
for (int i = 1; i <nums.length ; i++) {
nums[i] = nums[i&(i-1)]+1;
}
return nums;
}
更容易理解的做法,去掉最后一位,然后再加上最后一位是否为1:
public int[] countBits(int num) {
int[] nums = new int[num + 1];
nums[0] = 0;
for (int i = 1; i < nums.length; i++) {
nums[i] = nums[i>>1] + i%2;
}
return nums;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: