[leetcode] 338. Counting Bits

来源:互联网 发布:怎么下载苹果软件 编辑:程序博客网 时间:2024/05/16 00:39

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:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?
核心还是要找规律。

000000
-------------------
100011
-------------------
200101
300112
-------------------
401001
501012
601102
701113
-------------------
10001
910012
1010102
1110113
1211002
1311013
1411103
1511114

解法一:

第一个规律:如果是i是偶数,它的bit个数跟i/2个数相同,如果是i是奇数,bit个数是i/2个数+1。ps:难找啊。。。
class Solution {public:    vector<int> countBits(int num) {        vector<int> res{0};        for(int i=1; i<=num; ++i){            if(i%2==0) res.push_back(res[i/2]);            else res.push_back(res[i/2]+1);        }        return res;            }};


解法二:

000000 i&(i-1)
-------------------
100011 0000
-------------------
200101 0000
300112 0010
-------------------
401001 0000
501012 0100
601102 0100
701113 0110
-------------------
10001 0000
910012 1000
1010102 1000
1110113 1010
1211002 1000
1311013 1100
1411103 1100
1511114 1110

这个规律是i的bit个数是i&(i-1)这个数的bit个数+1。
class Solution {public:    vector<int> countBits(int num) {        vector<int> res{0};        for(int i=1; i<=num; ++i){            res.push_back(res[i&(i-1)]+1);        }        return res;            }};




0 0