Description
Given an integer num
, repeatedly add all its digits until the result has only one digit, and return it.
Examples:
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
Solution in Python
Python
class Solution:
def addDigits(self, num: int) -> int:
# If the input number is 0, return 0 immediately as the sum of digits of 0 is 0
if num == 0:
return 0
# Digital root formula:
# If num % 9 == 0 and num is not zero, return 9 (since 9 is the digital root of numbers like 9, 18, 27, etc.).
# Otherwise, return num % 9 which gives the digital root for all other cases.
return 9 if num % 9 == 0 else num % 9
Explanation:
- Base Case (num = 0):
If the input is 0, we return 0 immediately since no digit addition is needed. - Digital Root Concept:
The digital root of a number is the single digit you get by repeatedly summing its digits.
Mathematically, this can be reduced tonum % 9
, but with a special case:- If
num
is divisible by 9 and is not zero, the result is 9 (since 9 is the digital root of numbers like 9, 18, 27, etc.). - Otherwise, the result is
num % 9
.
- If
Solution in C++
C++
class Solution {
public:
int addDigits(int num) {
// If the input number is 0, return 0 immediately
if (num == 0)
return 0;
// Using the digital root formula:
// If num % 9 == 0 and num is not zero, return 9.
// Otherwise, return num % 9. This formula works because:
// - For any number, the digital root can be computed as the number mod 9.
// - Special case: when num is divisible by 9 (i.e., num % 9 == 0), the digital root is 9,
// unless num itself is zero.
// Return 9 if num is divisible by 9 and not zero, otherwise return num % 9.
return (num % 9 == 0) ? 9 : (num % 9);
}
};
Solution in Javascript
JavaScript
var addDigits = function(num) {
// If the input number is 0, return 0 immediately
if (num === 0) {
return 0;
}
// Using the digital root formula:
// The digital root can be calculated using modulo 9.
// If num is divisible by 9 and not zero, the result should be 9.
// Otherwise, the result is num % 9.
// Return 9 if num is divisible by 9 and not zero, otherwise return num % 9
return (num % 9 === 0) ? 9 : (num % 9);
};
Solution in Java
Java
class Solution {
public int addDigits(int num) {
// If the input number is 0, return 0 immediately
if (num == 0) {
return 0;
}
// Using the digital root formula:
// The digital root can be computed using modulo 9.
// If num is divisible by 9 and not zero, the result should be 9.
// Otherwise, the result is num % 9.
// Check if num is divisible by 9
if (num % 9 == 0) {
return 9; // Return 9 for multiples of 9
} else {
return num % 9; // Return the remainder for other cases
}
}
}