Sunday 17 July 2016

Count 1's

/*
    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
*/

 #include<iostream>  
 #include<stdlib.h>  
 using namespace std;  
 int* countBits(int num) {  
   int *arr = new int[num + 1];  
   //int *arr = (int *)malloc((num + 1) * sizeof(int));  
   int count, j;  
   arr[0] = 0;  
   for(int i = 1; i <= num; i++){  
     count = 0;  
     j = i;  
     while(j > 0){  
       if(j & 1 == 1){  
         count++;  
       }  
       j = j >> 1;  
     }  
     arr[i] = count;  
   }  
   return arr;  
 }  
 int main(){  
   int N = 5;  
   int *arr = new int[N + 1];  
   arr = countBits(N);  
   for(int i = 0 ; i <= N; i++){  
     cout << arr[i] << " ";  
   }  
   return 0;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive