Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce sum of digits recursively down to one digit number

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.

like image 965
HavingNoHead Avatar asked Oct 19 '25 03:10

HavingNoHead


1 Answers

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)); 
} 
like image 137
cdlane Avatar answered Oct 21 '25 18:10

cdlane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!