[英]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.