recursively sum the integers in an array

前端 未结 9 1004
不思量自难忘°
不思量自难忘° 2020-12-06 03:01

I have a program that I\'m trying to make for class that returns the sum of all the integers in an array using recursion. Here is my program thus far:

public         


        
相关标签:
9条回答
  • 2020-12-06 03:52

    This is the one recursive solution with complexity O(N).and with input parameter A[] only.
    You can handle null and empty(0 length) case specifically as Its returning 0 in this solution. You throw Exception as well in this case.


    /*
     * Complexity is O(N)
     */
    public int recursiveSum2(int A[])
    {
        if(A == null || A.length==0)
        {
            return 0;
        }
        else
        {
            return recursiveSum2Internal(A,A.length-1);
        }
    }
    private int recursiveSum2Internal(int A[],int length)
    {
        if(length ==0 )
        {
            return A[length];
        }
        else
        {
            return A[length]+recursiveSum2Internal(A, length-1);
        }
    }
    
    0 讨论(0)
  • 2020-12-06 03:56

    Try this if you don't want to pass the length of the array :

    private static int sumOfArray(int[] array) {
    
            if (1 == array.length) {
                return array[array.length - 1];
            }
    
            return array[0] + sumOfArray(Arrays.copyOfRange(array, 1, array.length));
        }
    

    Offcourse you need to check if the array is empty or not.

    0 讨论(0)
  • 2020-12-06 03:59

    The issue is that a[n-1] is an int, whereas sumOfArray expects an array of int.

    Hint: you can simplify things by making sumOfArray take the array and the starting (or ending) index.

    0 讨论(0)
提交回复
热议问题