gpt4 book ai didi

java - 需要编写递归函数比较两个数字存储在数组列表中的整数(java)

转载 作者:行者123 更新时间:2023-12-01 11:32:21 26 4
gpt4 key购买 nike

我只会使用迭代,因为它要容易 1000 倍,但为了这个家庭作业问题,我必须使用递归来比较两个整数。请注意,每个数字都存储为 arrayList,每个数字作为单个元素,因此:12345 = [1,2,3,4,5]。目前我有这个方法

public boolean isEqual(LargeInt otherLargeInt) {
if(digitList.size() != otherLargeInt.digitList.size()
return false;

因此,如果两个 arrayList 或“数字”的大小不匹配,那么它们显然不相等。我想做的是递归地比较每个数字的每个数字。根据我的理解,一旦其中一个数字不匹配,我就可以退出递归方法。有人可以把我推向正确的方向吗?我不确定如何处理此类问题。

最佳答案

public static boolean isEqual(List<Integer> first, List<Integer> second) {
if (first.size() != second.size())
return false;
else
// Creating new ArrayLists, so that the contents of the origianl lists remains unchanged
return isEqualHelper(new ArrayList<Integer>(first), new ArrayList<Integer>(second));
}

public static boolean isEqualHelper(List<Integer> first, List<Integer> second) {
// We have compared all the elements and didn't find any mismatch
if (first.isEmpty() && second.isEmpty())
return true;
else {
// Found mismatch
if (first.get(0) != second.get(0))
return false;
else {
// First element of both lists are OK, now check the rest
// of the list recursively
first.remove(0);
second.remove(0);
return isEqualHelper(first, second);
}
}
}

关于java - 需要编写递归函数比较两个数字存储在数组列表中的整数(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30295309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com