338. Counting Bits
2016-07-13 23:33
337 查看
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
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.Show
More Hint
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.
求0~num的数,每个数的二进制表示中分别有多少个1。
已经给提示了,2的幂次数1的个数只有1个,每次找出当前的数和哪个2的幂次最接近,把这个作为基数(其实就是1),
然后当前搜索数=(当前数-离当前数最近的2的幂次),这个当前搜索数一定在前面求出来了,直接加上就好。
public static int[] countBits(int num)
{
int[] arr=new int[num+1];
if(num<2)
{
for(int i=0;i<=num;i++)
arr[i]=i;
return arr;
}
arr[0]=0;
arr[1]=1;
arr[2]=1;
double lg2=Math.log10(2);
for(int i=3;i<=num;i++)
{
int power=(int) (Math.log10(i)/lg2);
int base=(int) Math.pow(2, power);
arr[i]=arr[base]+(i-base==0?1:arr[i-base]);
}
return arr;
}
return them as an array.
Example:
For
num = 5you 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.Show
More Hint
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.
求0~num的数,每个数的二进制表示中分别有多少个1。
已经给提示了,2的幂次数1的个数只有1个,每次找出当前的数和哪个2的幂次最接近,把这个作为基数(其实就是1),
然后当前搜索数=(当前数-离当前数最近的2的幂次),这个当前搜索数一定在前面求出来了,直接加上就好。
public static int[] countBits(int num)
{
int[] arr=new int[num+1];
if(num<2)
{
for(int i=0;i<=num;i++)
arr[i]=i;
return arr;
}
arr[0]=0;
arr[1]=1;
arr[2]=1;
double lg2=Math.log10(2);
for(int i=3;i<=num;i++)
{
int power=(int) (Math.log10(i)/lg2);
int base=(int) Math.pow(2, power);
arr[i]=arr[base]+(i-base==0?1:arr[i-base]);
}
return arr;
}
相关文章推荐
- Java并发编程总结4——ConcurrentHashMap在jdk1.8中的改进(转)
- CDOJ 28 补兵(kill) 解题报告
- 数据结构の基本概念和术语
- 线程死锁的问题
- 剑指Offer--063-二叉搜索树的第K个结点
- Java并发编程总结2——慎用CAS(转)
- unity模型法线反转问题
- 监控Linux性能的18个命令行工具
- unity3d第三天02(数组)
- Easyui 一些应用
- SSO-C#跨域单点登录(一)
- 想做Android Wear开发?你得先搞明白这四件事
- PhotoShop教程:制作玻璃水晶质感文字
- Linux中的可用内存指的是什么?
- ESP8266 AT指令开发篇(一)
- 巧用ASP.NET中的Web服务器控件
- error LNK2001: unresolved external symbol _IID_ISampleGrabberCB
- mysql优化--博森瑞
- hibernate之关联映射
- MySQL索引原理及慢查询优化