Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find middle digit in an integer in Java

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.

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.

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.. ");

Program Output:

digits: 1234567
no of digits 7
first 0
last 6
middle 3
middle digit: 4
like image 204
Waqas Mahmood Avatar asked Nov 29 '22 22:11

Waqas Mahmood


1 Answers

You can also do this in one pass. Idea is that first store the integer in the another variable. Then move two digits to the left in one integer while only one digit in the another one.

int a1 = 1234567;  
int a2 = a1;
int flag=0;

while(a2>0)
{
    a2/=10;               //Moves to the left by one digit
    if(a2==0)             //If there are odd no. of digits
    {
        flag=1;
        break;
    }
    a2/=10;               //Moves to the left by one digit
    a1/=10;               //Moves to the left by one digit
}
System.out.print(flag!=1?"No Mid Exists":a1%10);
like image 105
Sanket Makani Avatar answered Dec 15 '22 20:12

Sanket Makani