java - 检查list中的元素是否是12的倍数

标签 java recursion arraylist

给定一个列表,我试图递归地检查列表中的相邻元素是否是 12 的倍数,如果是,那么我需要检查列表中数字的剩余总和是否为奇数。例如,[6,6,5] 返回 true,[6,5,6,1] 返回 false。我在处理 [10, 7, 5, 5] 返回 true 的情况时遇到麻烦,因为 (7+5) = 12(12 的倍数) 和 (10+5) = 15(奇数)。这是我的代码。当元素索引为 0 和 1 时它有效,但当倍数位于中间时则无效。

public static boolean twoGroups(List<Integer> t) {
    if(t.size()  < 2 ) {
        return false;
    }

    if((t.get(0) * t.get(1)) % 12 == 0){
        List<Integer> i = new ArrayList<>(t);
        i.remove(0);
        i.remove(1);
        int works = checkSum(i, 0);
        if(works % 2 == 0) {
            return true;
        }else {
            return false;
        }

    }else { // I think this is where I am going wrong
        List<Integer> i = new ArrayList<>(t);
        List<Integer> newList = new ArrayList<>();
        newList.add(i.get(0));
        i.remove(0);
        return twoGroups(i);
    }

}


/*
 * returns true if the sum of the elements of the list is odd
 *Helper method
 */
public static int checkSum(List<Integer> t, int index) {
    if(t.size() == index) {
        return 0;
    }

    return t.get(index) + checkSum(t, index + 1);
}

我对我认为出错的部分发表了评论。请帮忙

最佳答案

我相信您有一些问题。

  1. 在第 6 行进行乘法运算 t.get(0) * t.get(1) % 12 == 0 。根据您给出的描述,您应该添加。 [10, 7, 5, 5] 会乘以 10 * 7,等于 70(12 的倍数)。
  2. 第 8 行和第 9 行 i.remove(0); i.remove(1);并没有像你想象的那样删除变量。首先,从 [10, 7, 5, 5] ->[7, 5, 5] 中删除 10(索引 0)。然后,删除 5(新索引 1)[7, 5]
  3. 将遍历到的变量添加到List<Integer> newList = new ArrayList<>();中但该变量从未被使用过。您应该使用该列表以及 List t 中的其余变量来求和。

关于java - 检查list中的元素是否是12的倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49395836/

相关文章:

java - 解析 Cookie 响应中的正则表达式

recursion - 在 coq 中递归反转假设

C++11 constexpr 函数编译器错误与三元条件运算符 (? :)

java - 如何从两个单独的 ArrayList 中删除重复的对象?

java - 插入到 Impala 表与写入 HDFS

java - 正则表达式 - 无法将西里尔字母与\w匹配

Java:简单的 BigDecimal 逻辑错误

java - Android ListView ,如何无边距定位 ListView ?

javascript - 在Javascript中获取文件夹和文件列表的最佳方法

java - 将数据存储在动态二维数组中