Get the Sum of Digits / Digital Root using Java

The challenge

Digital root is the recursive sum of all the digits in a number.

Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.

Examples

    16  -->  1 + 6 = 7
   942  -->  9 + 4 + 2 = 15  -->  1 + 5 = 6
132189  -->  1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
493193  -->  4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2

Tests cases

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class DRootExampleTest {
    @Test
    public void Tests() {
      assertEquals( "Nope!" , 7, DRoot.digital_root(16));
      assertEquals( "Nope!" , 6, DRoot.digital_root(456));
    }
}

The solution in Java

public class DRoot {
  public static int digital_root(int n) {
    
    // return the number if less than 10
    // this is to break out of the recursion loop
    if (n<10) return n;
    
    // set an output variable
    int out = 0;
    
    // while we still have numbers, loop
    while(n>0) {
      // increment our output by the base
      out += n % 10;
      // reduce the base by the same amount
      n = n / 10;
    }
  
    // return a recursion of the output
    return digital_root(out);
  }
}

Tags:
5 2 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments