[英]How to find highest odd number in an array and return 0 if no odd number is present in Java?
[英]Find the highest odd number in an array using recursion in java
public static int highestOdd(int [] arr, int index)
{
if(arr.length-1 == index) return arr[index];
int high = highestOdd(arr,index+1);
high = high > arr[index] ? high : arr[index];
return high;
}
索引始終傳遞為 0,因此此代碼將檢查包括偶數在內的所有數字,但我只想輸出最高的奇數。 我希望有人能幫助我 謝謝之前。
當用 arr[index] 替換 high 的值時,如果 arr[index] 值更高,只需檢查該值是否為奇數。 否則保持高值不變。 試試下面的代碼。 如果數組中沒有奇數,它將返回-1(假設數組的所有值都是正值,如果有可能是負值,那么您可以用整數 min 替換 -1)。 如果您不明白任何部分,請告訴我。
public static int highestOdd(int [] arr, int index) {
if(arr.length - 1 == index) return arr[index] % 2 > 0 ? arr[index] : -1;
int high = highestOdd(arr,index+1);
if(arr[index] % 2 > 0) high = high > arr[index] ? high : arr[index];
return high;
}
僅在遇到奇數整數時才更新高位。
public static int highestOdd(int[] arr, int index) {
// When last Integer is odd.
if (index == arr.length - 1 && arr[index] % 2 != 0) {
return arr[index];
}
// When last Integer is even.
else if(index == arr.length - 1)
return Integer.MIN_VALUE;
int high = highestOdd(arr, index+1);
//Update high only when current index has odd.
if(arr[index]%2 != 0){
high = high > arr[index] ? high : arr[index];
}
return high;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.