DEV Community

Isaac Tonyloi
Isaac Tonyloi

Posted on

1

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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!

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay