title: Find middle digit in an integer in Java
body: <p>I have an integer in java "1234567" and my program finds middle digit in a set of integer, is there more optimized way than below code?. Recently asked in java interview.</p>
  
  <p>What I have done is first find no of digits, first, last and middle indexes. Then find middle digit again iterating on same integer. Please advice some optimization.</p>
  
  <pre><code>int a1 = 1234567;
  int a = a1;
  
  // calculate length
  int noOfDigits = 0;
  while(a!=0)
  {
     a = a/10;
     noOfDigits++;
  }
  
  int first = 0;
  int last = noOfDigits-1;
  int middle = (first+last)/2;
  
  boolean midExists = ((a1%2)==1);
  System.out.println(" digits: "+a1);
  System.out.println(" no of digits "+noOfDigits);
  System.out.println(" first "+first);
  System.out.println(" last " + last);
  
  if(midExists)
  {
     System.out.println(" middle " + middle);
     int i = last;
     int middleDigit = 0;
     a = a1;
     while(i != middle)
     {
       a = (a / 10);
       middleDigit = (a%10);
       i--;
     }
     System.out.println("middle digit: " + middleDigit);
   }
   else
     System.out.println(" Mid not Exists.. ");
  </code></pre>
  
  <p>Program Output:</p>
  
  <pre><code>digits: 1234567
  no of digits 7
  first 0
  last 6
  middle 3
  middle digit: 4
  </code></pre>