Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Example 1:
Input: num = 38 Output: 2 Explanation: The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it.
Example 2:
Input: num = 0 Output: 0
Constraints:
0 <= num <= 231 - 1Follow up: Could you do it without any loop/recursion in O(1) runtime?
When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach repeatedly sums the digits of a number until we get a single digit. We simply keep doing the addition over and over, reducing the number at each step until only one digit remains.
Here's how the algorithm would work step-by-step:
def add_digits(number):
while number > 9:
sum_of_digits = 0
# Iterate until we have summed all of the digits
while number > 0:
sum_of_digits += number % 10
number //= 10
# Assign the digit sum to number so the loop continues
number = sum_of_digits
# The number must be a single digit, so we return the single digit
return numberThe goal is to repeatedly add the digits of a number until we get a single-digit result. The most efficient way is to avoid any explicit addition by leveraging a mathematical property based on the number's relationship to multiples of nine.
Here's how the algorithm would work step-by-step:
def add_digits(number):
if number == 0:
return 0
# Use modulo 9 to find the digital root.
remainder = number % 9
# If divisible by 9, the digital root is 9.
if remainder == 0:
return 9
# Otherwise, the remainder is the digital root.
return remainder| Case | How to Handle |
|---|---|
| Input is zero | Return zero directly as the sum of digits of 0 is 0. |
| Input is a single-digit number (1-9) | Return the number itself since it's already a single digit. |
| Large positive integer that could cause intermediate sums to overflow if not using 64 bit integers | Use 64-bit integers (long in Java, long long in C++) to accommodate potentially large intermediate sums, or use the congruence formula. |
| Maximum integer value (INT_MAX) | Handle the maximum integer value to avoid potential overflows in intermediate calculations, potentially using the congruence formula. |
| Negative Input | The problem states non-negative input; therefore, the solution should throw an error or return a predefined value (e.g., -1) indicating invalid input if it occurs. |
| Number with many 9s | A number with many 9s could lead to a long chain of additions; the congruence formula can address this directly. |
| Very small positive integer (1) | Return the input integer as it's already a single digit. |
| Integer close to zero (0) | Return the input integer as it's already a single digit. |