You are returning i
, but when the function goes back from the recursion, the value of i
is 1, then you return 1.
You have to return the result of the recursion instead.
return getDigits(...)
public static int getDigits(int digits, int i)
{
if (digits != 0)
{
i++;
getDigits(digits/10, i);
}
return i;
}
Step #1:
digits = 5428
i = 0
Step #2:
digits = 542
i = 1
[...] you increment i
, but you are not returning the result of your recursion, you are returning the value of i
on step #1.
Now, if you do like this:
public static int GetDigits(int number, int digits)
{
if (number == 0)
{
return digits == 0 ? 1 : digits;
}
return GetDigits(number / 10, ++digits);
}
You will be returning the value from the recursion.
Step #1:
number = 5428
digits = 0
Step #2:
number = 542
digits = 1
Step #3:
number = 54
digits = 2
Step #4:
number = 5
digits = 3
Step #5:
number = 0
digits = 4
Step #5 enters the condition of (number == 0)
and returns digits
, which at this step is 4
, to step #4.
Step #4 returns the result of GetDigits(number / 10, ++digits);
, which was step #5, to step #3.
Step #3 returns the result of GetDigits(number / 10, ++digits);
, which was step #4, to step #2.
Step #2 returns the result of GetDigits(number / 10, ++digits);
, which was step #3, to step #1.
Then step #1 returns the value 4
which was the result you got from the last interaction on the recursion.
Explanation on prefix and postfix operations in c# (++digits over digits++)