1. 题目描述
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.
【翻译过来】:给定一格非负整数i,需要输出从0-i,每个数对应二进制中1的个数。
2. 样例
num = 5
return [0,1,1,2,1,2]
3. 分析
其实题目理解起来非常简单:从0到i,我们需要每个数去计算其二进制里面1的个数,然后存储起来返回输出即可。
3.1. 普通算法
每个数计算二进制中1的个数可以使用模二的方法:该数不停除以2直到为0,在过程中如果当前数不能被2整除,则该位置就有一个1,使用一格计数器counter计算1的个数即可。
3.2. 相与的方法
每一个数i与i-1相与造成的效果都是:相与结果里面1的个数比i里面1的个数要少一个,即1的个数的表达式可以表示为:
array[i] - 1 = array[i&(i-1)]
array[i] = array[i&(i-1)] + 1
4. 源码
4.1. 普通算法
class Solution {
public:
int getBinaryOne(int num) {
int counter = 0;
while(num != 0) {
if (num % 2 != 0) {
counter++;
}
num /= 2;
}
return counter;
}
vector<int> countBits(int num) {
vector<int> result;
for (int i = 0; i <= num; i++) {
result.push_back(getBinaryOne(i));
}
return result;
}
};
4.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&(i-1)] + 1;
return ret;
}
};
5. 心得
第一种普通的算法非常容易去想,但是时间复杂度为O(nlogn),第二种算法真的很难想到,时间复杂度为O(n)。