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.

数字 n执行n=n&(n-1)后,将n的二进制表示中的最低位为1的改为0,其二进制位数减1,

解法一:

直观解法,时间复杂度为0(n*sizeof(int)),

vector countBits(int num) {
        vector res(num+1);
        if(num<0)
            return res;
        int times=0;
        for(int i=0;i<=num;i++){
            int n=i;
            times=0;
            while(n){
                times++;
                n=n&(n-1);
            }
            res[i]=times;
        }
        return res;
    }


解法二:

解法一没有利用已经算好的数据,

由n'=n&(n-1)后,将n的二进制表示中的最低位为1的改为0,其二进制位数减一,也就是bits(n)=bits(n')+1,而且n'

从前往后算,0为0,

 vector countBits(int num) {
        vector res(num+1);//初始值全为0
        if(num<0)
            return res;
        for(int i=1;i<=num;i++){
            res[i]=res[i&(i-1)]+1;
        }
        return res;
    }