Given an integer num
, repeatedly add all its digits until the result has only one digit, and return it.
Example:
- Input:
num = 38
- Output:
2
- Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Clarifying Questions
- Is the input always a non-negative integer?
- Yes, the problem statement implies that the input integer is non-negative.
- What should be returned if the input is 0?
- The process would indicate that 0 is returned since no further addition is required.
- Is there a limit to the size of the integer
num
?
- The problem does not specify a limit, so we should assume
num
can be a large non-negative integer.
Strategy
The task essentially requires iteratively summing the digits of the number until we get a single digit. There are two common approaches to solve this problem:
- Iterative Approach:
- Convert the number to a string to easily access each digit.
- Sum the digits repeatedly until a single digit is obtained.
- Mathematical Approach (Digital Root):
- Utilize the properties of numbers, specifically using the digital root congruence formula to find the result in constant time. The digital root for a number is given by
1 + (num - 1) % 9
.
Code
We’ll use the mathematical approach for its efficiency.
def addDigits(num: int) -> int:
if num == 0:
return 0
else:
return 1 + (num - 1) % 9
# Example usage
print(addDigits(38)) # Output: 2
Time Complexity
- Iterative Approach: O(log(num))
- Each iteration reduces the number of digits, hence the overall time complexity is proportional to the number of digits in
num
.
- Mathematical Approach: O(1)
- The formula
1 + (num - 1) % 9
directly computes the result in constant time.
In this implementation, we’ve chosen the mathematical approach due to its straightforward and efficient constant time complexity.
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?