Find average digit in integers in Java

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;

// 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
+4
source share
4 answers

. , integer . integer, .

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);
+8

"" . , : ( ) , , , "" :

int n = 1234;
int length = (int)(Math.log10(n)+1);

4 1234 5 12345.

: -. : int .

String asStr = Integer.toString(123456);

: ; !

, : , "1", "2",... , int 1, 2,... (. ASCII table, "1" - 49, )!

+9

There is less code in this answer, but I don’t think it will take much time:

int a1 = 12334;
int a = a1;
int middle = 0;
int noOfDigits = 0;

while (a1 != 0) {
    a1 = a1 / 10;
    noOfDigits++;
}
if (noOfDigits % 2 == 1) {
    for (int i = 0; i < (noOfDigits / 2) + 1; i++) {
        middle = a % 10;
        a = a / 10;
    }
    System.out.println(middle);
} else {
    System.out.println("No mid existing");
}
+4
source

Using only math

int num = 123406789;
int countDigits = (int)Math.ceil(Math.log10(num));
int midIndex = (int)Math.ceil(countDigits/2);
int x = num / (int)Math.pow(10, midIndex);
int middleDigit = x % 10;
System.out.println(middleDigit);
+1
source

Source: https://habr.com/ru/post/1676442/


All Articles