就是操作索引值
- public static void main(String[] args) {
- int[] a = {1,2,3,4,5,6,7,8};
- System.out.println(sum(a,a.length));
- }
- //很明显要操作索引值,可以从后往前加,也可以从前往后加
- public static int sum(int[] arr,int length){
- int sum = 0;
- if(length == 1)
- return arr[0];
- //从最后一个值(arr[length-1])逐渐往前加
- return sum = arr[length-1]+sum(arr,length-1);
-
- }
复制代码 |