DEV Community

özkan pakdil
özkan pakdil

Posted on

Sum of Digits / Digital Root

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. The input will be a non-negative integer.
Examples

16  -->  1 + 6 = 7
Enter fullscreen mode Exit fullscreen mode

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

Solution in java

    public static int digital_root(int n) {
        int r = n;
        while (r > 9) {
            r = String.valueOf(r)
                    .chars()
                    .map(Character::getNumericValue)
                    .sum();
        }
        return r;
    }

Enter fullscreen mode Exit fullscreen mode

Reference:https://www.codewars.com/kata/541c8630095125aba6000c00/train/java

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more