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
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
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.
题目:计算从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; }
相关文章推荐
- <<数学>>css文字是个不规则图形
- theano安装(二)windows安装visual studio 2010及cuda
- javaWEB项目感受
- Part 23 to 26 Routing in Angular
- ios学习笔记——操作队列 NSOperation
- 附录A
- Linux 常见环境变量、文件类型、权限管理
- poj 1201 Interval (查分约束)
- jqgrid快速入门之一:可编辑的单元格
- Could not insert new outlet connection问题解决方法
- zoj-3734 LIKE vs CANDLE 【树形dp】
- Redis vs Mencached
- Android 5.0的调度作业JobScheduler
- 视频图像处理基础知识1(双线性插值算法描述及实现)
- jenkins+maven+github持续集成
- VisualVM安装使用详解
- 分布式项目的几个需要注意的点
- 卷积神经网络
- Oracle触发器详解
- js判断银行卡号