0
votes

Im trying to implement a function that returns a natural number which is the sum of the digits within an entered natural number. I just keep on getting an infinite loop. I know i have to return the recursive call but i cant figure this out. Here is what i have so far:

private static NaturalNumber sumOfDigits(NaturalNumber n) {
        NaturalNumber zero = new NaturalNumber2(0);
        if (n.compareTo(zero) == 0) {
            return zero;
        } else {
            NaturalNumber z = new NaturalNumber2(n.divideBy10());
            n.divideBy10();
            z.add(sumOfDigits(n));

         // return ___;

        }
    }

What am i supposed to return? Returning z doesn't work

2
What do you need the NaturalNumber class for? - Cruncher
We're just recursing away like topsy today, aren't we? I'd suggest you review one of the 4-5 other threads started in the last 24 hours discussing basic recursion -- the same principles apply. - Hot Licks
@Cruncher - It makes it more complicated. - Hot Licks
@HotLicks divideBy10 is my new favourite method - Cruncher
@HotLicks Ive reviewed it and i have implemented this returning and int instead of a NN and it works. Im just trying to figure out how to return z.add(sumOfDigits(n)); but it gives me a void error - WestonBuckeye

2 Answers

1
votes

You are making the recursive call with n, the same number that was passed into your procedure. If you strip off a digit for z, then the recursive call has to be made with the rest of the digits.

You can strip off a digit with mod 10 and then get the rest of the digits by divide by 10. If you were using ints it would be:

return (n % 10) + sumOfDigits(n / 10);
0
votes

z.add(sumOfDigits(n)); should be z.add(sumOfDigits(n.divideBy10()));. The main point is in the recursion you only want to process the remainder of the answer, not the whole problem.