title: Binary Gap Program in Java
body: <p>My problem statement:</p>
  
  <blockquote>
    <p>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. The number 32 has binary representation 100000 and has no binary gaps.</p>
  </blockquote>
  
  <p>My code:</p>
  
  <pre><code>public class Abc {
  
      static void decToBinary(int n) {
  
          int[] binaryNum = new int[1000];
  
          // counter for binary array 
          int i = 0;
          while (n &gt; 0) {
              // storing remainder in binary array 
              binaryNum[i] = n % 2;
              n = n / 2;
              i++;
          }
          int ctr = 0, k = 0;
          ArrayList&lt;Integer&gt; al = new ArrayList&lt;Integer&gt;();
  
          // printing binary array in reverse order 
          for (int j = i - 1; j &gt;= 0; j--) {
              System.out.print(binaryNum[j]);
              if (binaryNum[j] == 0) {
                  k = j;
                  do {
                      ctr++;
                      k++;
                  } while (binaryNum[k] == 0);
                  al.add(ctr);
                  ctr = 0;
              }
          }
  
          for (int ii = 0; ii &lt; al.size(); ii++) {
              System.out.println(al.get(ii));
          }
      }
  
      // driver program 
      public static void main(String[] args) {
          int n = 1041;
          decToBinary(n);
      }
  }
  </code></pre>
  
  <p>I am trying to show the output of binary gap that is stored in my ArrayList.  But the output is quite different for a given input of 1041. I  don't know why it is storing 1,2,3,4; according to my logic it should store only the gap values 5 and 3 in case of input:1041, even though 5 and 3 are also stored in the ArrayList but at some other index.</p>
  
  <p>I think there is a problem in the do-while loop especially in <code>al.add(ctr)</code> but I haven't figured it out yet. </p>