I have an integer in java "1234567" and my program finds the middle digit in an integer set, is there a more optimized way than the code below ?. Recently asked in an interview with java.
What I did at first does not find the numbers, the first, last and average indices. Then find the second digit repeating again on the same integer. Consult some optimizations.
int a1 = 1234567;
int a = a1;
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
source
share