Solution 1 - Digital Root
The repeated sum of digits converges to the digital root: 0 if n=0 else 1 + (n - 1) % 9.
""" 0258.1 - Add Digits - Solution 1 - Digital Root """
class Solution:
def addDigits(self, n: int) -> int:
return 0 if n == 0 else 1 + (n - 1) % 9
if __name__ == "__main__":
assert Solution().addDigits(38) == 2Solution 2 - Iterative
Iteratively sum digits until one digit remains.
class Solution:
def addDigits(self, n: int) -> int:
while n >= 10:
s = 0
while n:
s += n % 10
n //= 10
n = s
return n