Is there a way to convert this iterative function that takes a Collection of Integer objects and adds these elements, into a recursive one?

huangapple go评论114阅读模式
英文:

Is there a way to convert this iterative function that takes a Collection of Integer objects and adds these elements, into a recursive one?

问题

最初,我们被鼓励使用递归来解决这个问题,但到目前为止,我只能想到一个迭代的方法。

  1. import java.util.*;
  2. public class Problem1 {
  3. static Integer add(Collection integers) {
  4. Integer sum = 0;
  5. Iterator iterator = integers.iterator();
  6. while (iterator.hasNext()) {
  7. sum = sum + (Integer) iterator.next();
  8. }
  9. return sum;
  10. }
  11. }
英文:

Originally, we were encouraged to solve the problem with recursion, but so far I can only think of an interative one.

  1. import java.util.*;
  2. public class Problem1 {
  3. static Integer add(Collection integers) {
  4. Integer sum = 0;
  5. Iterator iterator = integers.iterator();
  6. while (iterator.hasNext()) {
  7. sum = sum + (Integer) iterator.next();
  8. }
  9. return sum;
  10. }
  11. }

答案1

得分: 0

用一种方法是在递归过程中使用迭代器遍历然后移除元素。

  1. public class Problem1 {
  2. static Integer add(Collection integers) {
  3. Integer sum = 0;
  4. Iterator it = integers.iterator();
  5. if (!it.hasNext()) {
  6. return 0;
  7. }
  8. Integer number = (Integer)it.next();
  9. it.remove();
  10. sum += number + add(integers);
  11. return sum;
  12. }
  13. }
英文:

One way to do it is to use then remove the elements as you recurse through using an iterator.

  1. public class Problem1 {
  2. static Integer add(Collection integers) {
  3. Integer sum = 0;
  4. Iterator it = integers.iterator();
  5. if (!it.hasNext()) {
  6. return 0;
  7. }
  8. Integer number = (Integer)it.next();
  9. it.remove();
  10. sum += number + add(integers);
  11. return sum;
  12. }
  13. }

答案2

得分: 0

尝试这个。

  1. static Integer add(Iterator it) {
  2. if (!it.hasNext())
  3. return 0;
  4. else
  5. return (Integer)it.next() + add(it);
  6. }
  7. static Integer add(Collection integers) {
  8. return add(integers.iterator());
  9. }

  1. Collection integers = List.of(1, 2, 3, 4);
  2. System.out.println(add(integers));

输出

  1. 10
英文:

Try this.

  1. static Integer add(Iterator it) {
  2. if (!it.hasNext())
  3. return 0;
  4. else
  5. return (Integer)it.next() + add(it);
  6. }
  7. static Integer add(Collection integers) {
  8. return add(integers.iterator());
  9. }

and

  1. Collection integers = List.of(1, 2, 3, 4);
  2. System.out.println(add(integers));

output

  1. 10

huangapple
  • 本文由 发表于 2020年8月19日 15:24:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63481944.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定