sum of Digits through Recursion

980 views Asked by At

I am trying to make a recursive function which should return the sum of digits. The function should have only one argument. So far I have this;

public int sumDigits(int n) {
    if(n%10 == n) // last digit remains
        return n;

    else{
        int rightdigit; 
        rightdigit = n%10; // taking out the right most digit
        return rightdigit + (n/10); // adding it to everything on left
    }
}

The function works for some values, specifically 2 digit numbers. But It gives out really odd values for some numbers like 730 which comes out to be 73 when it should be 10.

I have worked it out on paper but cant figure out where I am going wrong. Any help would be much appreciated.

3

There are 3 answers

0
pb2q On BEST ANSWER

You aren't actually recursing. You've setup your base case, but when solving a problem recursively you should have code within the function that calls the function itself.

So you're missing a line that calls sumDigits, with a smaller argument.

Consider two important parts of a recursive soutlion:

  1. The base case. This is the end of recursion, at which point your recursions will begin to return, in your case creating a sum.
  2. The recursion: your recursive function will call itself, with a different argument, typically a smaller chunk of the problem.

Note that your problem fits this pretty well: you've got 2 cases in an if/else. Your base case is set up nicely, now in the other branch you'll want to actually recurse. It should be very obvious to you where to put the call to sumDigits.

0
M A On

Your method is not recursive. It should call itself in the last part:

return rightdigit + sumDigits(n / 10);

This adds the right-most digit to the recursively summed number of the left-most digits.

0
Balkrishna Rawool On

You forgot a call to sumDigits(). Change this line:

return rightdigit + (n / 10); 

to this:

return rightdigit + sumDigits(n / 10);