[英]Find if two Adjacent Array-elements are divisible by 10 using Recursion
如果 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;
}
divideByTen(arr, num - 1);
這會調用divideByTen
(遞歸)並丟棄結果。 遞歸不是魔術或特殊的; 你只是..調用一個方法。 它恰好與您使用的方法相同,僅此而已。 調用一個方法而不將其值賦給任何東西意味着返回值被丟棄。
據推測,您想要if (divideByTen(arr, num -1)) return true;
反而。
我試圖將 boolean 值存儲在一個變量中。 我認為在你的情況下它會返回 false 除非你的 if 條件最后不為真。
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;
}
為了實現遞歸方法,您應該始終考慮此問題的基本情況以及遞歸情況下應該發生的情況。
基本情況- 是遞歸應該終止時的邊緣情況(或一組邊緣情況),並且已知返回值是提前的,因為基本情況總是微不足道的情況。 這個問題的基本情況是沒有更多的元素。
遞歸情況- 是計算邏輯所在的地方,也是進行遞歸調用的地方。 在遞歸情況下,您需要評估當前的元素對,如果它們符合條件則返回結果,否則繼續進行遞歸調用。 為此,您可以使用||
運算符,稱為條件或。
請注意, Base case和Recursive case始終存在於任何遞歸實現中(顯式或隱式),牢牢理解這兩個概念將使您的生活更輕松。
似乎有些用戶以錯誤的方式解釋了問題陳述,因為兩個相鄰元素的總和可以被 10 整除而不是Two adjacent elements are divisible by 10 because the error in your code,盡管問題中沒有提到總和. 但這對算法沒有任何影響,我將展示這兩種實現。
兩個相鄰元素可以被 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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.