338. Counting Bits
来源:互联网 发布:北邮网络教育登录系统 编辑:程序博客网 时间:2024/06/05 06:38
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 timeO(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.
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
分析:
写出几个可以发现,后边的都是以2为幂的步长网上加一。
所有先求出小于num的最小二次幂,这部分按递归累加。
后半部分也是累加,只是更简单一点。
class Solution {
public:
vector<int> countBits(int num) {
vector<int> v1{0};
if(num==0) return v1;
v1.push_back(1);
if(num==1) return v1;
int p=2;
int i=0;
while(num>=p)
{
++i;
p=p*2;
}
p=p/2;
for(int j=0;j<i-1;++j)
{
int len =v1.size();
for(int t=0;t<len;++t)
{
v1.push_back(v1[t]+1);
}
}
for(int t=0; t<=(num-p);++t)
v1.push_back(v1[t]+1);
return v1;
}
};
- [leetcode] 338. Counting Bits
- 338. Counting Bits
- leetcode 338. Counting Bits
- LeetCodeOJ:338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode#338. Counting Bits
- 338. Counting Bits
- [LeetCode] 338. Counting Bits
- LeetCode 338. Counting Bits
- 338. Counting Bits
- [LeetCode]338. Counting Bits
- LeetCode-338. Counting Bits
- LeetCode *** 338. Counting Bits
- 338. Counting Bits
- (leetcode) 338. Counting Bits
- Swift 338. Counting Bits
- #leetcode#338. Counting Bits
- LeetCode 338. Counting Bits
- java中的抽象类
- bzoj 1180: [CROATIAN2009]OTOCI
- 网络时延的几个概念
- malloc原理和内存碎片
- 集合框架--ListIterator接口
- 338. Counting Bits
- 一些不错的WEB前端书籍
- .NET AOP (六)在编译阶段PostSharp
- ”伪集群“导致的Hibernate主键increment生成策略异常
- 编辑文章 - 博客频道 - CSDN.NET
- c++中使用fstream读写文件
- 5-19 PAT Judge (25分)
- extract things from text files
- 安卓开发基础--打招呼(事件的简单处理)