gpt4 book ai didi

java - 使用递归统计嵌套列表中奇数长度或偶数长度的列表数量

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:52 24 4
gpt4 key购买 nike

如何在 Java 中编写一个递归方法,它接受一个嵌套列表并计算奇数长度列表的数量和偶数长度列表的数量?到目前为止,我只得到了这个:

public class MyRekursion {
// [number of odd-lengthed lists, number of even-lengthed lists]
public static int[] countOddEven(List<Object> nestedList) {
int odd = 0;
int even = 0;
for (Object obj : nestedList){
if (obj instanceof List){
// ???
}
}

return new int[] { odd, even };
}
}

最佳答案

public class MyRecursion {
public static int[] countOddEven(List nestedList) {
int odd = 0;
int even = 0;

for (Object obj : nestedList) {
if (obj instanceof List) {
int[] res = countOddEven((List)obj);
odd += res[0];
even += res[1];
}
}

if (nestedList.size() % 2 == 1) {
++odd;
} else {
++even;
}

return new int[] { odd, even };
}
}

关于java - 使用递归统计嵌套列表中奇数长度或偶数长度的列表数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48340726/

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