Add Digits (Digital Root) Explained
Problem Statement
Given a non-negative integer num
, repeatedly add its digits until the result has only one digit. This single digit is called the digital root. For example, for 38, 3 + 8 = 11, then 1 + 1 = 2, so the digital root is 2. This problem can be solved iteratively or using a mathematical congruence formula.
Example
Input: num = 38
Output: 2
Explanation: 3 + 8 = 11, 1 + 1 = 2.
Code
Java
Python
JavaScript
public class Solution { public int addDigits(int num) { return num == 0 ? 0 : 1 + ((num - 1) % 9); } public static void main(String[] args) { Solution sol = new Solution(); System.out.println(sol.addDigits(38)); // 2 } }
def add_digits(num): if num == 0: return 0 return 1 + ((num - 1) % 9) # Example usage print(add_digits(38)) # 2
function addDigits(num) { if (num === 0) return 0; return 1 + ((num - 1) % 9); } // Example usage console.log(addDigits(38)); // 2
Explanation
- Use the congruence formula: digital root of
num
is1 + ((num - 1) % 9)
unlessnum
is 0. - This formula derives from the fact that
num % 9
equals the sum of its digits modulo 9. - For
num = 0
, the digital root is 0. - The formula avoids iterative digit summing for efficiency.
Note
The congruence formula provides an O(1) solution, much faster than iterative summing (O(log num)). Ensure the input is non-negative to avoid undefined behavior.