DEV Community

Isaac Tonyloi
Isaac Tonyloi

Posted on

Repeatedly add all its digits until the result has only one digit.

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Example 1:

Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2 
Since 2 has only one digit, return it.
Example 2:

Input: num = 0
Output: 0
Enter fullscreen mode Exit fullscreen mode

Constraints:


0 <= num <= 231 - 1
Enter fullscreen mode Exit fullscreen mode

Follow up: Could you do it without any loop/recursion in O(1) runtime?

Solution

The digital root of a non-negative integer is the single digit value obtained by repeatedly summing the digits of the number until a single digit value is obtained. The digital root is also known as the repeated digital sum.

The mathematical formula to calculate the digital root of a number is:

digital_root(n) = 1 + (n - 1) % 9

/**
 * @param {number} num
 * @return {number}
 */
var addDigits = function(num) {
    if (num === 0) {
        return 0;
        } else {
            return 1 + (num - 1) % 9;
        }

};

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
kalkwst profile image
Kostas Kalafatis

Great post! The explanation of the digital root and the provided formula are very helpful. However, it might be useful to provide some additional explanation or examples of how the formula works. Also, I noticed that you used the #datastructures tag, but since this problem is related to an algorithmic concept, it might be more appropriate to use the #algorithms tag instead. Keep up the good work!