Reduce sum of digits recursively down to one digit number

Lior Roz :

How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion? I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:

class sum_of_digits 
{ 

    static int sum_of_digit(int n) 
    {  
        if (n == 0) 
            return 0; 
        return (n % 10 + sum_of_digit(n / 10)); 
    } 

    public static void main(String args[]) 
    { 
        int num = 12345; 
        int result = sum_of_digit(num); 
        System.out.println("Sum of digits in " +  
                           num + " is " + result); 
    } 
} 

This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.

cdlane :

do you think it is possible to make it work without an additional method?

Why can't we just let the recursion do the work for us and simply say:

static int sum_of_digit(int n) 
{  
    if (n < 10) 
        return n;

    return sum_of_digit(n % 10 + sum_of_digit(n / 10)); 
} 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86092&siteId=1