LeetCode 第 338 题 (Counting Bits)
2016-04-19 09:30
411 查看
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; } };
相关文章推荐
- AntiXSS - 支持Html同时防止XSS攻击
- 【<meta name="" content=">】的作用
- ThinkPHP if条件下做判断注意的地方。
- 大数据时代的压缩表现形式
- Tomcat类加载器架构
- 如何创建处理器池之享元模式
- 跨站脚本攻击(XSS)
- 如何查看 SQL Server 占用内存
- [C语言][LeetCode][61]Rotate List
- Linux下which、whereis、locate、find命令的区别
- 3dsmax2014如何导入图片作为参考
- 2015阿里移动推荐算法比赛第一赛季总结
- jsf - javax.validation.ConstraintViolationException
- AP聚类
- 测试用例分析tests
- 海康摄像头安装步骤
- Netty
- Windows Server 2012 NIC Teaming
- oracle怎么实现分页比较好
- 获取LedgerDimention各个维度的组合值