Thursday, June 2, 2016

Counting Bits

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.


This is a DP problem. The first two numbers, 0 and 1, have 0 and 1 bits. From then on, each time we hit a number that is a power of 2, we have one more carries, but all other digits are repeated again from the very beginning.

    0        1
    0        1
                     10     11
                       1       2
100    101   110   111
    1        2       2       3


public int[] countBits(int num) {
        int[] bits = new int[num + 1];
        if (num < 0)
            return bits;
        bits[0] = 0;
        if (num == 0)
            return bits;
        bits[1] = 1;
        int index = 0;
        for (int i = 2; i <= num; i++) {
            if (isPowerOfTwo(i))
                index = 0;
            bits[i] = 1 + bits[index++];
        }
        return bits;
    }
    
    private boolean isPowerOfTwo(int num) {
        return (num & (num - 1)) == 0;
    }

No comments:

Post a Comment