Counting Bits

来源:互联网 发布:网络维护外包 编辑:程序博客网 时间:2024/06/05 03:18


     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.


想法1:
比如 7 = 0111
7^4 = 0111^0100 = 0011
即7的1个数比3的1个数多1。

    public int[] countBits(int num) {        int[] dp = new int[num+1];        dp[0] = 0;        int bit = 1;        for(int i=1;i<=num;i++)        {            int k = (int) Math.pow(2, bit-1);            if(i%k==0 && i/k==2){bit++;k*=2;}            dp[i] = dp[i ^ k]+1;        }//      for(int i : dp){System.out.println(i);}        return dp;    }



想法2:
比如 7 = 0111
7^(7-1) = 0111&0110 = 0110
即7的1个数比6的1个数多1。
如果最低位是1,减一后则最低位为0, &后肯定会少一个1
如果最低位为0,最低位往前第一个为1的那一位x一定会变成0,&后x位少一个1

    public int[] countBits(int num) {        int[] dp = new int[num+1];        for(int i=1;i<=num;i++)        {            dp[i] = dp[i & (i-1)]+1;        }        return dp;    }
0 0
原创粉丝点击