diff --git a/src/main/java/org/fundacionjala/coding/cynthia/DigitalRoot.java b/src/main/java/org/fundacionjala/coding/cynthia/DigitalRoot.java new file mode 100644 index 0000000..e302b9d --- /dev/null +++ b/src/main/java/org/fundacionjala/coding/cynthia/DigitalRoot.java @@ -0,0 +1,52 @@ +package org.fundacionjala.coding.cynthia; + +/** + * In this kata, you must create a digital root function. + *
+ * A 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 two digits, + * continue reducing in this way until a single-digit number is produced. + * This is only applicable to the natural numbers. + *
+ * Here's how it works (Ruby example given): + *
+ * sumOfDigits(16) + * => 1 + 6 + * => 7 + *
+ * sumOfDigits(942) + * => 9 + 4 + 2 + * => 15 ... + * => 1 + 5 + * => 6 + *
+ * sumOfDigits(132189) + * => 1 + 3 + 2 + 1 + 8 + 9 + * => 24 ... + * => 2 + 4 + * => 6 + *
+ * sumOfDigits(493193) + * => 4 + 9 + 3 + 1 + 9 + 3 + * => 29 ... + * => 2 + 9 + * => 11 ... + * => 1 + 1 + * => 2 + */ + +public class DigitalRoot { + + /** + * @param num with the digits. + * @return the sum of digits. + */ + public int sumOfDigits(int num) { + int res = 0; + while (num != 0) { + res += num % 10; + num = num / 10; + } + return res >= 10 ? sumOfDigits(res) : res; + } +} diff --git a/src/test/java/org/fundacionjala/coding/cynthia/DigitalRootTest.java b/src/test/java/org/fundacionjala/coding/cynthia/DigitalRootTest.java new file mode 100644 index 0000000..a358c92 --- /dev/null +++ b/src/test/java/org/fundacionjala/coding/cynthia/DigitalRootTest.java @@ -0,0 +1,25 @@ +package org.fundacionjala.coding.cynthia; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * Created by Cynthia on 9/11/2017. + */ +public class DigitalRootTest { + + /** + * + */ + @Test + public void tests() { + DigitalRoot digital = new DigitalRoot(); + assertEquals(7, digital.sumOfDigits(16)); + assertEquals(6, digital.sumOfDigits(942)); + assertEquals(6, digital.sumOfDigits(132189)); + assertEquals(2, digital.sumOfDigits(493193)); + assertEquals(9, digital.sumOfDigits(54)); + assertEquals(1, digital.sumOfDigits(100)); + } +}