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
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)妙用
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.
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; }
相关文章推荐
- 007.php数据类型转换即$_GET[]
- Matlab读取视频并处理成帧保存
- mysql数据库优化 数据库结构优化
- Java Session超时设置
- lftp的用法
- 用UIButton的类方法ButtonWithType创建时调用的是initWithFrame方法
- servlet 学习(六)
- HIPS实现
- 命令集锦
- CAS原子操作实现无锁及性能分析
- WOJ 1605 Distance on Tree(莫队算法)
- linux基础学习之 gsoap calc 例程(2)
- 20145238-荆玉茗 《Java程序设计》第一次实验报告
- 20145122《JAVA开发环境的熟悉》实验报告
- OpenLayers中layer图层概念和实践
- EditText设置圆角
- [RxJS] Observables can throw errors
- android:代码中动态添加子布局
- Android里的网格空隙
- Android里的网格空隙