Leetcode--338. Counting Bits
来源:互联网 发布:怎么修改淘宝付款密码 编辑:程序博客网 时间:2024/06/05 16:36
题目
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’的个数等于除了最低位之外的‘1’的个数加上最低位‘1’的个数,即ret[n] = ret[n>>1] + n%2,具体代码:
代码
class Solution { public: vector<int> countBits(int num) { vector<int> ret(num+1, 0); for(int i=1; i<=num; ++i) ret[i] = ret[i>>1] + i%2; return ret; } };
阅读全文
0 0
- [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
- 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
- Leetcode 338. Counting Bits
- LeetCode 338. Counting Bits
- Elasticsearch检索分类深入详解—基础篇
- HDU1213 How Many Tables 并查集入门
- 导航 4
- 有名信号量实现读者-写着问题(写者优先)
- 基于aiohttp web框架的微信公众号开发(项目)
- Leetcode--338. Counting Bits
- git的push与fetch
- HTTP协议详解
- Linux-视频监控系统(12)-移植到树莓派中
- OpenCV文档翻译--相机标定
- hdu1087最长递增子序列dp
- 论文总结——In Situ Visualization at Extreme Scale Challenges and Opportunities
- 【MVC】走向MVC模式
- Farm Irrigation HDU