LeetCode 第 338 题 (Counting Bits)
来源:互联网 发布:数据结构书与算法java 编辑:程序博客网 时间:2024/06/07 02:14
LeetCode 第 338 题 (Counting Bits)
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.
这道题也不难,计算一个数的 1 的位数时可以借用以前计算过的结果。下面是代码
class Solution {public: vector<int> countBits(int num) { vector<int> ret; ret.push_back(0); for(int i = 1; i <= num; i++) { int bits = ret[i >> 1] + (i & 1); ret.push_back(bits); } return ret; }};
1 0
- LeetCode 第 338 题 (Counting Bits)
- leetcode:bits:Counting Bits(338)
- 【LeetCode-338】Counting Bits
- leetcode-338-Counting Bits
- Leetcode 338 Counting Bits
- LeetCode 338 :Counting Bits
- [leetcode-338]Counting Bits
- 【LeetCode-338】 Counting Bits
- LeetCode 338 Counting Bits
- Counting Bits leetcode 338
- [LeetCode 338] Counting Bits
- LeetCode-338:Counting Bits
- LeetCode-338:Counting Bits
- LeetCode[338] Counting Bits
- LeetCode#338 Counting Bits
- LeetCode 338 Counting Bits
- LeetCode 338 Counting Bits
- Leetcode #338 Counting Bits
- ThinkPHP if条件下做判断注意的地方。
- studyphp环境软件Nginx隐藏index.php和Pathinfo模式配置例子
- Tomcat类加载器架构
- 【<meta name="" content=">】的作用
- (转)Android N 开发者预览版 2 发布
- LeetCode 第 338 题 (Counting Bits)
- 2015阿里移动推荐算法大赛总结
- 通过 Autostereograms 案例学习 OpenGL 和 OpenCL 的互操作性 英文原文:OpenGL / OpenCL Interoperability : A Case Study U
- SQL语句的MINUS,INTERSECT和UNION ALL
- jQuery转换JS原生代码
- Android中的cursor
- Java实现自定义链表
- 修改分库中的数据记录
- 2440挂载nfs