Sum of Digits Until a Single Digit [Solution]
Here’s a Python implementation of the add_digits
function:
def add_digits(num: int) -> int:
if num == 0:
return 0
elif num % 9 == 0:
return 9
else:
return num % 9
# Example usage:
result = add_digits(123)
print(result) # Output: 6 since 1 + 2 + 3 = 6.
result = add_digits(38)
print(result) # Output: 2 since 3 + 8 = 11 and 1 + 1 = 2.
result = add_digits(9875)
print(result) # Output: 2 since 9 + 8 + 7 + 5 = 29 and 2 + 9 = 11 and 1 + 1 = 2.
result = add_digits(1)
print(result) # Output: 1.
This solution takes advantage of the mathematical pattern
where the result is equal to the remainder
of the number divided by 9
,
except when the number is divisible by 9
.
In that case, the result is 9
.
Time Complexity:
The time complexity is O(1
),
Space Complexity:
The space complexity is O(1
).