Created
October 21, 2011 11:54
-
-
Save salzig/1303652 to your computer and use it in GitHub Desktop.
Rekursive Summe von Array Elementen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.List; | |
public class Test { | |
/** | |
* @author Ben Rexin <[email protected] | |
*/ | |
public static void main(String[] args) { | |
List<Integer> array = Arrays.asList(1,2,3,4); | |
System.out.println(sum(array)); | |
} | |
/** | |
* @author Ben Rexin <[email protected] | |
* @param list of Integer | |
* @return Integer | |
*/ | |
public static Integer sum(List<Integer> list) { return sum(list,0,0); } | |
/** | |
* @author Ben Rexin <[email protected] | |
* @param list of Integer | |
* @param index as position within list | |
* @param accu sum of elements in list from 0 to index | |
* @return Integer | |
*/ | |
public static Integer sum(List<Integer> list, Integer index, Integer accu) { | |
if (list == null || index == null || accu == null) throw new IllegalArgumentException(); | |
return index == list.size() ? accu : sum(list, index +1, accu + list.get(index)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment