如果 2 個相鄰的數字除以 10,我有一個數字陣列應該回傳 true。
現在,我的代碼總是回傳false。
我的嘗試:
public static boolean divideByTen(int arr[], int num) {
int i = num - 1;
if (i > 0) {
divideByTen(arr, num - 1);
if (arr[i] arr[i - 1] % 10 == 0)
return true;
}
return false;
}
uj5u.com熱心網友回復:
divideByTen(arr, num - 1);
這會呼叫divideByTen(遞回)并丟棄結果。遞回不是魔法或特殊的。你只是..呼叫一個方法。它恰好與您使用的方法相同,但僅此而已。呼叫方法而不將其值分配給任何東西意味著回傳的值被丟棄。
大概,你想要if (divideByTen(arr, num -1)) return true;的。
uj5u.com熱心網友回復:
我試圖將布林值存盤在一個變數中。我認為在您的情況下,除非您的 if 條件最后不為真,否則它將回傳 false。
public static void main (String[] args)
{
int[] a = new int[] {1, 2, 3, 4, 1, 2, 30, 2};
System.out.println(divideByTen(a, a.length - 1));
}
public static boolean divideByTen(int arr[], int num){
boolean flag = false;
if(num < 1){
return flag;
}
flag = divideByTen(arr, num -1);
if(num > 0){
if((arr[num-1] arr[num]) % 10 == 0){
flag = true;
}
}
return flag;
}
uj5u.com熱心網友回復:
如何處理遞回
為了實作遞回方法,您應該始終考慮這個問題的基本情況,并且應該在遞回情況下發生。
基本情況- 是遞回應該終止的邊緣情況(或一組邊緣情況),并且已知回傳值是提前的,因為基本情況總是微不足道的情況。此問題的基本情況是沒有更多元素時。
遞回案例- 是計算邏輯所在的位置,以及進行遞回呼叫的位置。在遞回情況下,您需要評估當前的元素對,如果它們匹配條件回傳結果,否則繼續遞回呼叫。為此,您可以使用
||稱為 Conditional-OR 的運算子。
請注意,基本案例和遞回案例總是存在于任何遞回實作中(顯式或隱式),對這兩個概念的深刻理解將使您的生活更輕松。
執行
似乎某些用戶以錯誤的方式解釋了問題陳述,因為兩個相鄰元素的總和可被 10 整除,而不是由于代碼中的錯誤,兩個相鄰元素可被 10 整除,盡管問題中未提及總和. 但這對演算法沒有任何影響,我將展示這兩種實作。
兩個相鄰的元素可以被 10 整除:
public static boolean hasAdjacentDivisibleByTen(int[] arr) {
if (arr.length < 2) return false; // or throw an exception because there's no two adjacent elements in the given list
return hasAdjacentDivisibleByTen(arr, arr.length - 1);
}
public static boolean hasAdjacentDivisibleByTen(int[] arr, int pos) {
if (pos == 0) return false; // Base case - no more elements to check left
// Recursive case - return current result or proceed with next call (if result is false)
return arr[pos] % 10 == 0 && arr[pos - 1] % 10 == 0 || hasAdjacentDivisibleByTen(arr, pos - 1);
}
兩個相鄰元素之和可被 10 整除:
public static boolean hasAdjacentSumDivisibleByTen(int[] arr) {
if (arr.length < 2) return false;
return hasAdjacentSumDivisibleByTen(arr, arr.length - 1);
}
public static boolean hasAdjacentSumDivisibleByTen(int[] arr, int pos) {
if (pos == 0) return false; // Base case - no more elements to check left
// Recursive case - return current result or proceed with next call (if result is false)
return (arr[pos] arr[pos - 1]) % 10 == 0 || hasAdjacentDivisibleByTen(arr, pos - 1);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/532359.html
標籤:爪哇数组算法递归
下一篇:集合的最大子集數
