Tuesday, 21 March 2017

Find longest sequence of zeros in binary representation of an integer


 A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.

Write a function:

int solution(int N);

that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.

For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.

Solution:


 public class Test {  
      private static long maxConsecutiveZeroes(int x) {  
           boolean flagOne = false;  
           long count = 0, max = 0;  
           //Loop until x becomes 0.  
           while (x != 0) {  
                if ((x & 1) == 1) {  
                     flagOne = true;  
                     if (count > max) {  
                          max = count;  
                     }  
                     count = 0;  
                } else if (flagOne) {  
                     count += 1;  
                } else {  
                     count += 1;  
                }  
                x = x >> 1;//Move ht binary digits to right side bit by bit.  
           }  
           return max;  
      }  
      public static void main(String strings[]) {  
           System.out.println(maxConsecutiveZeroes(16));  
           System.out.println(maxConsecutiveZeroes(9));  
           System.out.println(maxConsecutiveZeroes(14));  
           System.out.println(maxConsecutiveZeroes(222));  
           System.out.println(maxConsecutiveZeroes(3));  
           System.out.println(maxConsecutiveZeroes(4));  
           System.out.println(maxConsecutiveZeroes(1041));  
      }  
 }  

Output:


 4  
 2  
 1  
 1  
 0  
 2  
 5  

Enjoy Coding.

No comments:

Post a Comment