![]() |
VOOZH | about |
You are given a number n, you need to find the digital root of n.
Examples :
Input: n = 1
Output: 1
Explanation: Digital root of 1 is 1.
Input: n = 99999
Output: 9
Explanation: The sum of digits of 99999 is 45 which is not a single digit number, hence the sum of digits of 45 is 9 which is a single digit number.
Table of Content
The approach is focused on calculating the digital root of a number, which is the result of summing the digits repeatedly until a single-digit value is obtained. Here's how it works conceptually:
Example:
For a number like 1234
9
Time Complexity: O(d), where ddd is the number of digits in nnn.
Auxiliary Space: O(1)
We know that every number in the decimal system can be expressed as a sum of its digits multiplied by powers of 10. For example, a number represented as abcd can be written as follows:
abcd = a * 10 ^ 3 + b * 10 ^ 2 + c * 10 ^ 1 + d * 10 ^ 0
We can separate the digits and rewrite this as:
abcd = a + b + c + d + (a * 999 + b * 99 + c * 9)
abcd = a + b + c + d + 9 * (a * 111 + b * 11 + c)
This implies that any number can be expressed as the sum of its digits plus a multiple of 9.
So, if we take modulo with 9 on both side,
abcd % 9 = (a + b + c + d) % 9 + 0This means that the remainder when abcd is divided by 9 is equal to the remainder where the sum of its digits (a + b + c + d) is divided by 9.
If the sum of the digits itself consists of more than one digit, we can further express this sum as the sum of its digits plus a multiple of 9. Consequently, taking modulo 9 will eliminate the multiple of 9 until the sum of digits becomes a single-digit number.
As a result, the digital root of a number can be found using modulo 9. If the result of the modulo operation is zero for a non-zero number, then the digital root is 9.
9
Time Complexity: O(1)
Auxiliary Space: O(1)