Counting Bits 计算二进制形式中的1的个数
来源:互联网 发布:mac totalfinder 编辑:程序博客网 时间:2024/06/07 07:30
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?
首先,我们计算一部分数的二进制中的1的个数看看。
如图,我们可以发现[4-7]的结果是前面[0-3]的值+1
[8-15]的结果是前面[0-7]的值+1
所以,我们得到了如何根据前面已经计算好的值,计算当前值的规律。
运行时间:
代码:
public class CountingBits { public int[] countBits(int num) { int[] cache = new int[num + 1]; int begin = 1; int count = 0; while (begin <= num) { int i = 0; for (; i < Math.pow(2, count); i++) { if (begin + i <= num) { cache[begin + i] = cache[i] + 1; } else { return cache; } } begin = begin + i; count++; } return cache; }}
1 0
- Counting Bits 计算二进制形式中的1的个数
- 338. Counting Bits 数字的二进制中1的个数
- (LeetCode)Counting Bits -- 求二进制中1的个数
- 求二进制形式中的1的个数
- leetcode 338. Counting Bits(C语言,二进制中1的个数)39
- 计算二进制形式中1的个数的经典算法
- 338. Counting Bits(计算整数二进制表示中1的位数)
- [LeetCode] Counting Bits 计算二进制表示法中1的位数
- LeetCode 338. Counting Bits(计算二进制数中1的位数)
- leetcode 338. Counting Bits 位计算 + 统计二进制1的数量
- leetcode-338. Counting Bits 统计十进制数字的二进制表示中1的个数,列表的定义,奇偶判断
- Java实例4 - 快速计算二进制数中1的个数(Fast Bit Counting)
- Java实例4 - 快速计算二进制数中1的个数(Fast Bit Counting)
- 二进制形式中1的个数
- 整数二进制形式中1的个数
- 计算一个32位整数的二进制形式中1的个数
- 计算int型数据的二进制形式中——1的个数
- 输入一个整形数,计算这个数二进制形式里面1的个数。
- OpenGL FBO 对象
- AC-自动机(AC-Automachine)
- Tomcat设置JDK路径
- OpenGL 纹理映射
- 玻璃旅行
- Counting Bits 计算二进制形式中的1的个数
- OpenGL 渲染管线理论
- 字符串匹配KMP算法的理解(详细)
- js属性控件
- Java工具类——常用正则表达式工具RegexpUtils
- 使用Instruments来监控应用内存分配
- OpenGL 的渲染流水线
- apache2.4版本服务器在本机上配置虚拟站点
- Mp4V2 AAC/PCM 封装MP4 iOS 很容易,用FFmpeg也一样,直接写文件。