Sunday, October 15, 2017

338. 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.
Solution:
1. DP
   1.Obviously, count[1111] = count[1000]+count[111]
   2. And any number that is power of 2 should have only 1 of digit 1. Like 1,10,100...
   3. Besides those power of 2 numbers, all others should follow the first observation.
2. DP
   1. Count[1111] = count[111] + count[1], count[1110] = count[111]+count[0]
    => count[n] = count[n/2]+count[n%2] or count[n]=count[n>>1]+count[n&1]

   
 public int[] countBits(int num) {  
     int[] res=new int[num+1];  
     int factor=1;  
     for(int i=1;i<=num;i++){  
       if((i &(i-1))==0){  
         factor=i;  
       }  
       res[i]=res[i%factor]+1;  
     }  
     return res;  
   }  
 public int[] countBits(int num) {  
     int[] res=new int[num+1];  
     for(int i=1;i<res.length;i++){  
       res[i] = res[i/2] + (i %2);  
     }  
     return res;  
   }  

No comments:

Post a Comment