英文:
Is there a way to convert this iterative function that takes a Collection of Integer objects and adds these elements, into a recursive one?
问题
最初,我们被鼓励使用递归来解决这个问题,但到目前为止,我只能想到一个迭代的方法。
import java.util.*;
public class Problem1 {
static Integer add(Collection integers) {
Integer sum = 0;
Iterator iterator = integers.iterator();
while (iterator.hasNext()) {
sum = sum + (Integer) iterator.next();
}
return sum;
}
}
英文:
Originally, we were encouraged to solve the problem with recursion, but so far I can only think of an interative one.
import java.util.*;
public class Problem1 {
static Integer add(Collection integers) {
Integer sum = 0;
Iterator iterator = integers.iterator();
while (iterator.hasNext()) {
sum = sum + (Integer) iterator.next();
}
return sum;
}
}
答案1
得分: 0
用一种方法是在递归过程中使用迭代器遍历然后移除元素。
public class Problem1 {
static Integer add(Collection integers) {
Integer sum = 0;
Iterator it = integers.iterator();
if (!it.hasNext()) {
return 0;
}
Integer number = (Integer)it.next();
it.remove();
sum += number + add(integers);
return sum;
}
}
英文:
One way to do it is to use then remove the elements as you recurse through using an iterator.
public class Problem1 {
static Integer add(Collection integers) {
Integer sum = 0;
Iterator it = integers.iterator();
if (!it.hasNext()) {
return 0;
}
Integer number = (Integer)it.next();
it.remove();
sum += number + add(integers);
return sum;
}
}
答案2
得分: 0
尝试这个。
static Integer add(Iterator it) {
if (!it.hasNext())
return 0;
else
return (Integer)it.next() + add(it);
}
static Integer add(Collection integers) {
return add(integers.iterator());
}
和
Collection integers = List.of(1, 2, 3, 4);
System.out.println(add(integers));
输出
10
英文:
Try this.
static Integer add(Iterator it) {
if (!it.hasNext())
return 0;
else
return (Integer)it.next() + add(it);
}
static Integer add(Collection integers) {
return add(integers.iterator());
}
and
Collection integers = List.of(1, 2, 3, 4);
System.out.println(add(integers));
output
10
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论