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.
Input: 2
Output: [0,1,1]
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.

Now, It is time to think before we write our code onto a paper. We read about the binary representation in college. A binary number is a special type of representation of a number in a binary format where the bit can be 0 or 1. You had an idea that the computer system also understands the 0's and 1's. 0's mean an inactive bit and 1's mean an active bit. Let's understand the easiest way to calculate the number using the pictorial diagram.
This is something that looks like 2's multiples and the remainder will go into the stack. When we pop the remainders from the stack it will look like the same as shown in picture 27 = 11011. 
Let's verify if the above binary digit is equal to the number or not with the help of binary to decimal conversion.
27 = 1*24 + 1*2+ 0*22 + 1 * 21 + 1 * 20
This is the process of binary representation numbers.
Our problem statement is a bit similar but we need to just count only the active bits (1) for each number 0 to num which will be passed by the user.
If you observe the above chart then you come to know that there is some pattern which follows that every certain number drops to 1. If you look more into the pattern it will help us to resolve from the bottom-up approach. This graph gives us more information, if you look into the graph 2, 4, 8, 16 all 1 which means that 4/2 = 2. For an even number, you can directly fetch half of the number 1's count. For an odd number, it will fetch half of the number 1's count + 1.

Number012345
1’s count011212
Let's do the code and understand it in deep-dive
public static int[] countBits(int num) {
    int[] resultBit = new int[num+1];
    resultBit[0] = 0;
    for (int i = 1; i < num+1; i++) {
        if (i%2 != 0)
            resultBit[i] = resultBit[i/2] +1;
        else
            resultBit[i]=resultBit[i/2];
    }
    return resultBit;
}
I hope you are understanding the solution to the given problem. We will come up with a new challenge soon.

Comments

Popular posts from this blog

Recursion

Stack

Data Structure & Algorithm