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。
因为最近在研究树状数组,被他的精妙所震撼。他巧妙的将一个数的二进制0与1的个数赋予新的含义。
int LowBit(int x) { return x & (-x); }
树状数组学习笔记:
看到了这个题,很自然的联想到LowBit的使用。
思路:记忆化搜索+LowBit
对于LowBit(x):
假设x的末尾0的个数为k则LowBit是计算2^k,同时也是计算末尾1在的位置(即所表示的数)
i | bit | 2^k |
1 | 01 | 1 |
2 | 10 | 2 |
3 | 11 | 1 |
4 | 100 | 4 |
5 | 101 | 1 |
6 | 110 | 2 |
7 | 111 | 1 |
8 | 1000 | 8 |
9 | 1001 | 1 |
10 | 1010 | 2 |
11 | 1011 | 1 |
12 | 1100 | 4 |
13 | 1101 | 1 |
14 | 1110 | 2 |
15 | 1111 | 1 |
16 | 10000 | 16 |
当i与2^k相等时,意味着只有一个1,输出1
当i与2^k不相等时,比如我们看i=15,此时2^k=1,即末尾的1代表1,我们把末尾的1“去掉”,1111-->1110
即转化为求14的二进制数1的个数(当然得加上删除的1),也就是我们得利用先前求得的来计算i的二进制数1的个数。
#include <iostream> #include <vector> using namespace std; class Solution { public: int LowBit(int x) { return x & (-x); } vector<int> countBits(int num) { vector<int>vec; vec.push_back(0); for (int i = 1; i <= num; ++i) { if (i == LowBit(i)) { vec.push_back(1); } else { vec.push_back(vec[i - LowBit(i)] + 1); } } return vec; } }; int main() { Solution s; vector<int>vec = s.countBits(16); for (auto iter = vec.begin(); iter != vec.end(); iter++) { cout << *iter << endl; } return 0; }
63ms