338. Counting Bits

来源:互联网 发布:英雄无敌3 mac 编辑:程序博客网 时间:2024/06/13 05:03

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。

因为最近在研究树状数组,被他的精妙所震撼。他巧妙的将一个数的二进制0与1的个数赋予新的含义。
int LowBit(int x){return x & (-x);}

树状数组学习笔记:
http://blog.csdn.net/x_iya/article/details/8943264

看到了这个题,很自然的联想到LowBit的使用。
思路:记忆化搜索+LowBit

对于LowBit(x):
假设x的末尾0的个数为k则LowBit是计算2^k,同时也是计算末尾1在的位置(即所表示的数)
ibit2^k
101121023111410045101161102711118100089100111010102111011112110041311011141110215111111610000160特殊处理下,直接输出0
当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

1 0