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

Implement a function to find the final result.

Function Signature:

def add_digits(num: int) -> int:
    """
    Add digits of the given number until a single digit is obtained.

    Parameters:
    - num: A non-negative integer.

    Returns:
    - int: The single-digit result.
    """
    # Your code here

Example:

# Input: num = 123
# Output: 6
# Explanation: The process is: 1 + 2 + 3 = 6.

# Input: num = 38
# Output: 2
# Explanation: The process is: 3 + 8 = 11, 1 + 1 = 2.

# Input: num = 9875
# Output: 2
# Explanation: The process is: 9 + 8 + 7 + 5 = 29, 2 + 9 = 11, 1 + 1 = 2.

# Input: num = 1
# Output: 1

Note:

  • Many people would solve this problem using a loop or recursion. However, if possible, please find a solution that does not involve any loop or recursion and has a constant runtime complexity of O(1).

Instructions:

  • Write the add_digits function to solve the problem.
  • Implement your solution in Python.
  • Provide clear comments in your code.
  • Discuss the time and space complexity of your solution.

As always, we’ll share our solution to this problem tomorrow. Stay tuned 😊