Add Digits - Problem

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

Follow up: Could you do it without any loop/recursion, in O(1) runtime?

Input & Output

Example 1 — Two Digit Number
$ Input: num = 38
Output: 2
💡 Note: 3 + 8 = 11, then 1 + 1 = 2. Since 2 has only one digit, return 2.
Example 2 — Single Digit
$ Input: num = 0
Output: 0
💡 Note: 0 already has only one digit, so return 0 immediately.
Example 3 — Multiple Iterations
$ Input: num = 999
Output: 9
💡 Note: 9 + 9 + 9 = 27, then 2 + 7 = 9. Since 9 has only one digit, return 9.

Constraints

  • 0 ≤ num ≤ 2³¹ - 1

Visualization

Tap to expand
Add Digits - Digital Root INPUT Given Integer: 38 Digits Breakdown: 3 8 = 11 Continue with 11: 1 1 = 2 ALGORITHM STEPS 1 Check Base Case If num == 0, return 0 2 Digital Root Formula Use O(1) math formula 1 + (num - 1) % 9 Digital Root = 1 + (38-1) % 9 = 1 + 37 % 9 = 1 + 1 = 2 3 Why It Works num % 9 gives remainder 38 = 4*9 + 2 Digital root cycles: 1-9 Every multiple of 9 --> 9 4 Return Result Single digit: 2 FINAL RESULT Digital Root of 38: 2 Verification: 38 --> 3 + 8 = 11 11 --> 1 + 1 = 2 Single digit reached: OK Output: 2 Key Insight: The digital root follows a pattern based on modulo 9. Any number's digital root equals (n-1) % 9 + 1 for n > 0. This is because 10 = 1 (mod 9), so each digit position contributes only its face value to the remainder. Time Complexity: O(1) | Space Complexity: O(1) - No loops or recursion needed! TutorialsPoint - Add Digits | Optimal Solution (Digital Root Formula)
Asked in
Adobe 15 Microsoft 12 Amazon 8
195.0K Views
Medium Frequency
~10 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen