2017-05-05 56 views
4

我在java「1234567」中有一個整數,我的程序在一組整數中找到中間數字,有沒有比下面的代碼更優化的方式?最近在java面試中問到。在Java中找到一個整數的中間數字

我所做的是先找到數字,第一,最後和中間索引號。然後再次找到中間數字迭代在相同的整數。請建議一些優化。

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

程序的輸出:

digits: 1234567 
no of digits 7 
first 0 
last 6 
middle 3 
middle digit: 4 
+0

char/length?2-1? –

+3

int numberOfDigits = String.valueOf(a1).length();而不是while循環 – rilent

+0

我將轉換爲字符串並獲取字符串的中間一個。 – kism3t

回答

8

你也可以做到這一點的一個通行證。想法是,首先將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); 
+0

有趣的做法。 – vefthym

+3

現在,這是答案:)謝謝@Sanket Makani –

+2

你在最後一行有一個'='太多 – XtremeBaumer

9

你的 「數學」 工作正常。有一兩件事你可以:計算長度你的電話號碼前期,避免「迭代」數量的兩倍之內(中位數) - 讓您可以或確定的數字,這個數字是偶奇沒有「迭代「數量:

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表; 1'在其數值爲49時)!

+2

'System.out.println(str.charAt(str.length()/ 2));'會輸出正確的值,即4在這種情況下 – XtremeBaumer

+0

感謝您的答案,我必須做到這一點,而不使用像length()這樣的語言方法,或者將其轉換爲數組或字符串 –

+5

@WaqasMahmood,那麼你應該在你的問題 – XtremeBaumer

4

這個答案有更少的代碼,但不會採取太多的表現,我認爲:

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"); 
} 
+3

'a1 = 1233'。中間是否存在這個?你的代碼打印'是'。 –

+0

耶不是最好的支票。但與op使用相同 – XtremeBaumer

+0

noOfDigits長度檢查是否正確,以中間存在或不存在爲準@GhostCat發佈.. –

1

只使用數學

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

我猜數學方法不允許... – vefthym

+0

道歉..我忘記提及,在我的問題中,語言方法不允許:) –

相關問題