Math Fundamentals18 sections · 814 units
Open in Course

Problem - Add Digits

(Digital root via mod 9)

Given an integer num, repeatedly add all its digits until the result has only one digit. Return that digit. This is called the digital root.

Example: num = 38. First 3 + 8 = 11. Then 1 + 1 = 2. Return 2. Another example: num = 123 gives 1 + 2 + 3 = 6, which is already single digit.

There is a brute force way (loop) and a clever mod 9 trick. I will show you both. The mod 9 solution runs in constant time.