class Solution:
def addDigits(self, num: int) -> int:
# Digital root formula for base 10
if num == 0:
return 0
else:
return 1 + (num - 1) % 9
class Solution {
public:
int addDigits(int num) {
if (num == 0) return 0;
else return 1 + (num - 1) % 9;
}
};
class Solution {
public int addDigits(int num) {
if (num == 0) return 0;
else return 1 + (num - 1) % 9;
}
}
var addDigits = function(num) {
if (num === 0) return 0;
else return 1 + ((num - 1) % 9);
};
You are given a non-negative integer num
. Your task is to repeatedly add all its digits until the result has only one digit, then return that single-digit result.
num = 38
, you compute 3 + 8 = 11
, then 1 + 1 = 2
, so the answer is 2
.num
is a non-negative integer (i.e., num ≥ 0
).
At first glance, this problem seems to require repeatedly summing the digits of num
until only one digit remains. The most direct approach is to use a loop: extract each digit, sum them, and repeat until the number is a single digit. However, the problem hints at finding a more efficient solution, possibly without explicit iteration.
Upon further thought, this process is related to a mathematical concept called the "digital root." The digital root of a number is the value obtained by an iterative process of summing its digits until a single-digit number is produced. There is a well-known formula for computing the digital root in base 10, which can give us the answer in constant time.
The challenge is to recognize this mathematical shortcut and apply it, moving from a brute-force, iterative solution to an elegant, O(1) time solution.
Let's break down the steps to solve this problem, starting with the brute-force method and then explaining the optimized approach.
num
has more than one digit, do the following:sum = 0
.num
(using num % 10
), add it to sum
, and remove the digit from num
(using integer division by 10).num = sum
and repeat.num
is a single digit, return it.1 + (num - 1) % 9
(except for num = 0
, where the result is 0).num
greater than 0, the answer is 1 + (num - 1) % 9
.We use the optimized method for its clarity and efficiency.
Let's use num = 38
as an example:
Using the digital root formula:
1 + (38 - 1) % 9 = 1 + 37 % 9 = 1 + 1 = 2
num
.The "Add Digits" problem can be solved by simulating the digit-summing process, but recognizing its mathematical structure allows us to use the digital root formula for an elegant, constant-time solution. This insight transforms a potentially iterative task into a direct computation, making the solution both efficient and concise.