有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

递归需要编写递归函数,比较两个数字存储在ArrayList中的整数(java)

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

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

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


共 (3) 个答案

  1. # 1 楼答案

    通常,您希望比较每个列表中的第一个数字,如果它们相等,则递归,传入列表的其余部分(除第一个元素外的所有内容)。至少在Lisp、Scheme、Scala等函数式语言中通常是这样的。如果你没有一个方法来给出“列表的其余部分”,那么你就必须使用索引。从0开始,递归时传递“index+1”

  2. # 2 楼答案

    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);
            }
        }
    }
    
  3. # 3 楼答案

    您可以使用下面的比较,继续递归,直到元素相等

    调用以进行比较:

    compare(list1, list2, 0);
    

    递归比较

    boolean compare(List<Integer> list1, List<Integer> list2, int i){
        // if list size reached return true
        if(i == list1.size()){
           return true;
        }
        // else if elements at index are equal call compare(list1, list2, index + 1)
        if(list1.get(i).equals(list2.get(i))){
            return compare(list1, list2, i+1);
        }        
        else{
            return false;
        }
    }