0

I need to make a recursive function that returns the number of digits in the array.

This is what I got so far

public static int Rec(int[] arr, int size)
{
    int numbers = 0;        

    if(size > 0)
    {
    numbers = String.valueOf(arr[size]).length() + Rec(arr, size-1); //length of digits in array
    }

    return numbers;

}

But the problem is that it crashes the debug when it gets there.

I think it is the String.valueOf that makes it crash, any ideas on how I could get the number of digits in x-th place of the array? (number of digits in arr[x])

ifloop
  • 8,079
  • 2
  • 26
  • 35
Boris
  • 65
  • 1
  • 1
  • 9
  • 2
    Java applications normally don't crash silently. So you should get a Stacktrace, please post it here. And please describe your application a little bit more. It is currently hard to understand what you're trying to achieve. – Tom Oct 28 '14 at 12:27
  • Check this - [Way to get number of digits in an int?](http://stackoverflow.com/questions/1306727/way-to-get-number-of-digits-in-an-int) – Subhrajyoti Majumder Oct 28 '14 at 12:29

2 Answers2

1

Issue is you were using 5 - size and you might be having few elements in array then 5 (atleast before you edited your question). You are using numbers variable remember with every recursive call its going to reset with 0.

Try calling Rec(array, array.length - 1) from your main method:

public static int Rec(int[] arr, int size) {
    if (size >= 0) {
        return 1 + (int) Math.floor(Math.log10(arr[size])) + Rec(arr, size - 1);//or to keep it simple use String.valueOf(arr[size]).length() instead of 1 + (int) Math.floor(Math.log10(arr[size]))
    }
    return 0;
}
SMA
  • 36,381
  • 8
  • 49
  • 73
  • The 5-size was an error of pressing ctrl - z to many times, I called Rec(array, arrSize -1), now it doesn't crash, but it does not give the result it should, if I input for example 1, 22, 5, 4 it returns 4 instead of 5 – Boris Oct 28 '14 at 13:05
  • Compare it with what i pasted and you should have 5 in output. – SMA Oct 28 '14 at 13:08
  • I found the solution at the end, thanks for everything tho, the calling was really important. – Boris Oct 28 '14 at 13:22
  • i mentioned it in my post "Try calling Rec(array, array.length - 1) from your main method" Hope it helped. – SMA Oct 29 '14 at 06:15
0

Calling the function: Rec(arr, arrSize - 1)

public static int Rec(int[] arr, int size)
    {
        int numbers = 0;        

        if(size >= 0)
        {

        numbers += String.valueOf(arr[size]).length() + Rec(arr, size -1); //length of digits in array

        }

        return numbers;

    }

This works

Boris
  • 65
  • 1
  • 1
  • 9