Search code examples
javaalgorithmrecursion

Sum of Digits / Digital Root using Recursion


I am trying to add the digits using the below code.
For example if my input is 678 my output should be 3.

eg.

digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6

package codewars;
        
public class test 
{
    static int sum(int s)
    {
        int n=s;
        int add=0;
        while(n % 10 > 0)       
        {
            add = n % 10 + add;
            n = n / 10;
            //System.out.println("num is "  +n );
        }
                 
        if(add / 10 > 0)
        {
            System.out.println(add);
            sum(add);
            System.out.println("if block");
        }
                
        return add;
    }
        
    public static void main(String[] args) 
    {
        int result = test.sum(678);
        System.out.println(result);
    }
      
}

I want to call the sum function recursively till the sum consists of single digits only.


Solution

  • Something more close to your own algorithm. Does not use mod anywhere though, instead it transforms the number into a string and adds all the numeric values of the characters together each pass. Easier to understand but maybe not as performant(? to be tested).

    public class Test{
                static int sum(final int s)
                {
                    final String numbers = String.valueOf(s);
                    final int amountOfDigits = numbers.length();
                    int sum = Character.getNumericValue(numbers.charAt(0));
                    for(int i = 1; i < amountOfDigits; i++) {
                        sum += Character.getNumericValue(numbers.charAt(i));
                    }
                    
                    if(sum > 9) {
                        return sum(sum);    
                    } else {
                        return sum;
                    }
                }
    
                public static void main(String[] args) 
                {
                    int result = Test.sum(678);
                    System.out.println(result);
                }
    }
    

    To fix your own code just add return to the recursive call. Otherwise you always return the sum of all the digits of the initial number, which you only want to do when there is only one digit left.

    static int sum(int s)
                {
                    int n=s;
                    int add=0;
                    while(n%10 > 0)        
                    {
                        add = (n%10) +add;
                        n = n/10;
                        System.out.println("num is "  +n );
                    }
    
                    if(add/10 > 0)
                    {
                        System.out.println(add);
                        return sum(add);
                    }
                    return add;
                }