• 50.6%

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

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

Hint:

1. A naive implementation of the above process is trivial. Could you come up with other methods?
2. What are all the possible results?
3. How do they occur, periodically or randomly?
4. You may find this Wikipedia article useful.

https://discuss.leetcode.com/topic/21498/accepted-c-o-1-time-o-1-space-1-line-solution-with-detail-explanations/2

Accepted C++ O(1)-time O(1)-space 1-Line Solution with Detail Explanations

The problem, widely known as digit root problem, has a congruence formula:

https://en.wikipedia.org/wiki/Digital_root#Congruence_formula

For base b (decimal case b = 10), the digit root of an integer is:

• dr(n) = 0 if n == 0
• dr(n) = (b-1) if n != 0 and n % (b-1) == 0
• dr(n) = n mod (b-1) if n % (b-1) != 0

or

• dr(n) = 1 + (n - 1) % 9

Note here, when n = 0, since (n - 1) % 9 = -1, the return value is zero (correct).

From the formula, we can find that the result of this problem is immanently periodic, with period (b-1).

Output sequence for decimals (b = 10):

~ input: 0 1 2 3 4 …

output: 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 ….

Henceforth, we can write the following code, whose time and space complexities are both O(1).

https://discuss.leetcode.com/topic/36921/c-3-lines-implementation

C++ 3 lines implementation

https://discuss.leetcode.com/topic/28791/3-methods-for-python-with-explains

3 methods for python with explains

Iteration method

Digital Root
this method depends on the truth:

N=(a[0] 1 + a[1] 10 + …a[n] * 10 ^n),and a[0]…a[n] are all between [0,9]

we set M = a[0] + a[1] + ..a[n]

and another truth is that:

1 % 9 = 1

10 % 9 = 1

100 % 9 = 1

so N % 9 = a[0] + a[1] + ..a[n]

means N % 9 = M

so N = M (% 9)

as 9 % 9 = 0,so we can make (n - 1) % 9 + 1 to help us solve the problem when n is 9.as N is 9, ( 9 - 1) % 9 + 1 = 9

https://discuss.leetcode.com/topic/21834/o-1-solution-with-mod-operation

O(1) solution with mod operation

If an integer is like 100a+10b+c, then (100a+10b+c)%9=(a+99a+b+9b+c)%9=(a+b+c)%9

https://discuss.leetcode.com/topic/30490/no-loop-recursion-o-1-runtime-just-one-line-python-code

No loop/recursion, O(1) runtime, just one line python code