如果将不用循环如何计算1累加到100做一个变化,不再用连续的自然数做累加,而是一个int数组,如何实现呢?思路还是老思路,只不过上次我们是从后往前(由100往下累加到1),现在我们反过来了,是从头往后:
public class Recursion {
// 数组下标索引,从0开始
private static int count = 0;
// 递归的退出条件是下标索引=数组长度-1,此时返回数组值
public static int add(int[] toAdds, int index) {
if (count < toAdds.length - 1) {
return toAdds[count] + add(toAdds, count++);
}
return toAdds[count];
}
public static void main(String[] args) {
// 还是计算1+...+100
int[] toAdds = new int[100];
for (int i = 0; i < toAdds.length; i++) {
toAdds[i] = i + 1;
}
System.out.println(add(toAdds, count));
// 随便计算一个数组
toAdds = new int[]{1, 5, 7, 33, 101};
// 重新初始化数组索引
count = 0;
System.out.println(add(toAdds, count));
}
}
运行结果:
5050
147