Advertisement
apl-mhd

Binary gap codility

Aug 3rd, 2016
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. int solution(int N){
  2.  
  3.  
  4.  
  5.  
  6.  
  7.     int  count = 0, i, j, temp, gapIndex = 0, gapCount = 0;
  8.  
  9.    int  binaryConvertArray[100], binaryGap[100];
  10.  
  11.    /*decimal to binary convert section*/
  12.  
  13.     while(N !=0 ){
  14.  
  15.         binaryConvertArray[count] = N % 2;
  16.  
  17.         N /=2;
  18.         count++;
  19.  
  20.  
  21.     }
  22.  
  23.  
  24.     /* binary array reverse section*/
  25.  
  26.     j = count -1, i = 0;
  27.  
  28.     while(i < j){
  29.  
  30.         temp = binaryConvertArray[i];
  31.  
  32.         binaryConvertArray[i] = binaryConvertArray[j];
  33.         binaryConvertArray[j] = temp;
  34.         i++;
  35.         j--;
  36.  
  37.  
  38.     }
  39.  
  40.  
  41.  
  42.  
  43.     /*searching gap indexr*/
  44.  
  45.     for(i = 1; i < count; i++){
  46.  
  47.         if(binaryConvertArray[i] == 0){
  48.  
  49.              gapCount++;
  50.  
  51.  
  52.         }
  53.  
  54.         if(binaryConvertArray[i] == 1){
  55.  
  56.            // printf("gapcount =  %d \n", gapCount);
  57.  
  58.             binaryGap[gapIndex] = gapCount;
  59.             gapCount = 0;
  60.             gapIndex++;
  61.  
  62.         }
  63.  
  64.     }
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.     if(gapIndex > 1){
  72.  
  73.  
  74.         if(binaryGap[0] > binaryGap[1]){
  75.  
  76.             return binaryGap[0];
  77.         }
  78.  
  79.         else{
  80.  
  81.           return  binaryGap[1];
  82.         }
  83.     }
  84.  
  85.     else if(binaryGap[0] == 0){
  86.  
  87.         return 0;
  88.     }
  89.  
  90.     else{
  91.  
  92.         return binaryGap[0];
  93.     }
  94.  
  95.  
  96.  
  97.  
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement