Dare2Solve
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit. Return that single-digit result.
The problem can be solved using a straightforward mathematical approach based on the properties of numbers rather than iterative digit summation. The key observation is that the result of repeatedly summing the digits of a number until a single digit is obtained follows a pattern known as the "digital root." This can be computed using modular arithmetic.
Digital Root Concept:
1 + (num - 1) % 9
. This formula gives the correct result for all numbers except 0
, which requires special handling.num
is 0
, return 0
directly.Implementation:
num = 0
.Edge Cases:
num
is 0
, where the formula would incorrectly return 9
without a special case check.O(1)
. The calculation is done in constant time using a simple mathematical operation.
O(1)
. No extra space is used beyond the input variable.
class Solution {
public:
int addDigits(int num) {
return 1 + (num - 1) % 9;
}
};
class Solution:
def addDigits(self, num: int) -> int:
if num == 0:
return 0
return 1 + (num - 1) % 9
class Solution {
public int addDigits(int num) {
return 1 + (num - 1) % 9;
}
}
/**
* @param {number} num
* @return {number}
*/
var addDigits = function(num) {
return 1 + (num - 1) % 9;
};