對于這個問題,我需要輸入 10 個整數,然后列印出唯一的數字。我解決這個問題的方法是掃描我們正在檢查的數字后面的所有數字,看看是否有任何重復。這是我到目前為止的代碼。如果我輸入像“1234567891”這樣的數字,它只會列印“pl:1”,因為我在運行演算法之前添加了第一個數字。關于為什么它不起作用的任何假設?
//setup
Scanner input = new Scanner(System.in);
String text = input.nextLine();
text = text.replaceAll("\\s",""); //remove all spaces
int[] intDigits = new int[10];
//turn the string into an int array
for (int i = 0; i < 10; i ){
intDigits[i] = text.charAt(i) - '0';
}
input.close();
//add the first number since it will always be unique with my algorithm
String pl = intDigits[0] " ";
//check every number behind the one we are checking, if all the numbers are not equal to the one we are checking, then add it to the string of unique numbers.
for (int i = 1; i < 10; i ) {
int count = 0;
for (int j = i-1; j >= 0; j--) {
if (intDigits[i] != intDigits[j]) {
count ;
}
}
if (count == i-1) {
pl = intDigits[i];
}
}
System.out.println("\n\npl: " pl);
uj5u.com熱心網友回復:
問題在于if (count == i-1). 相反,它應該是if (count == i)。
由于您正在檢查 index 1,1如果沒有重復, count 將為(j=0) 。
同樣,如果沒有重復,則i=2計數將為2(j=1,0)。其余的也一樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342776.html
標籤:爪哇
上一篇:通用型別串列的多執行緒排序
下一篇:使用數學方法重寫數學函式
