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.
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?
解题思路
这道题给我们一个整数n,然我们统计从0到n每个数的二进制写法的1的个数,存入一个一维数组中返回;
思路一:按位与:x&(x-1)
//count记录x二进制表示下1的个数
int count=0;
while(x){
x=x&(x-1);
++count;
}
class Solution {
public:
vector<int> countBits(int num) {
vector<int> Ans;//保存[0,1,2,---num]二进制表示下1的个数
int x;
int count;
for(int i=0;i<=num;++i){
count=0;
x=i;
while(x){
x=x&(x-1);
++count;
}
Ans.push_back(count);
}
return Ans;
}
};
但是考虑到上述代码中存在相当大 的重复计算 比如7二进制下表示为111;
第一次进入循环x=111(二进制表示) 十进制下为7
进入后x=110(二进制表示) 十进制下为6
第二次进入循环x=110(二进制表示) 十进制下为6
进入后x=110(二进制表示) 十进制下为4
以此类推,重复运算了之前已经计算过的数字,因而可以直接获取之前6在二进制下1的个数即可。
c++代码2:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> Ans(num+1,0);//初始化0
for(int i=1;i<=num;++i)//从1开始
Ans[i]=Ans[i&(i-1)]+1;//简化 不重复计算
return Ans;
}
};
当然,题目中有提示,也可以采用奇数偶数来进行处理
若为偶数:最低位为0 ;
若为奇数:最低位为1;
再考虑去除最低位后的数值;
if(i%2==0)//偶数
Ans[i]=Ans[i/2];
else//奇数
Ans[i]=Ans[i/2]+1;
C++代码3:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> Ans(num+1,0);//初始化0
for(int i=1;i<=num;++i){//从1开始
if(i%2==0)//偶数
Ans[i]=Ans[i/2];
else//奇数
Ans[i]=Ans[i/2]+1;
}
return Ans;
}
};