Search code examples
javarecursion

Recursion: sum digits of a number until there is a single digit left


How can I sum digits of a number in a recursive manner until there is only a single digit left?

Example: with the input 9234, the result would be 9 because 9 + 2 + 3 + 4 = 18 and then 1 + 8 = 9.

This is my code for the moment but I want to sum until there is only a single digit

int getsum(int n) {
   return n == 0 ? 0 : n % 10 + getsum(n/10);
}

Solution

  • There are several possibilities, here is one of them:

    public static int getSum(int n) {
         int s = getSumHelper(n); // your original (private) method
         while (s > 9)
             s = getSumHelper(s);
         return s;
    }
    

    EDIT: Your original code for completeness, because there seems to be confusion.

    private static int getSumHelper(int n) {
        return n == 0 ? 0 : n % 10 + getSumHelper(n/10);
    }