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评论77阅读模式
英文:

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

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:

确定