Digital Root - Problem

Write a function that takes a positive integer and repeatedly sums its digits until only a single digit remains. This single digit is called the digital root.

For example:

  • 161 + 6 = 7 (single digit, so return 7)
  • 383 + 8 = 111 + 1 = 2 (return 2)
  • 9429 + 4 + 2 = 151 + 5 = 6 (return 6)

Requirements: Implement both iterative and recursive solutions.

Input & Output

Example 1 — Basic Case
$ Input: n = 942
Output: 6
💡 Note: Step-by-step: 942 → 9 + 4 + 2 = 15 → 1 + 5 = 6. Since 6 is a single digit, return 6.
Example 2 — Single Digit Input
$ Input: n = 7
Output: 7
💡 Note: Since 7 is already a single digit, return it directly without any processing.
Example 3 — Multiple Iterations
$ Input: n = 9999
Output: 9
💡 Note: 9999 → 9 + 9 + 9 + 9 = 36 → 3 + 6 = 9. The digital root is 9.

Constraints

  • 1 ≤ n ≤ 109
  • n is a positive integer

Visualization

Tap to expand
Digital Root Problem OverviewINPUT942Multi-digit numberGoal: Reduce to single digitby repeatedly summing digitsDigit Extraction:9 (hundreds place)4 (tens place)2 (units place)Sum: 9 + 4 + 2 = 15ALGORITHM STEPS1Start: n = 9422Sum digits: 9 + 4 + 2 = 153Check: 15 ≥ 10? Yes, continue4Sum digits: 1 + 5 = 65Check: 6 < 10? Yes, done!Alternative Approaches:• Iterative: Loop until single digit• Recursive: Call function with sum• Mathematical: 1 + (n-1) % 9FINAL RESULT6Digital RootSingle digit achieved!Process complete.Verification:942 → 15 → 6 ✓Time: O(log n) to O(1)Space: O(1) to O(log n)Key Insight:The digital root represents the iterative sum of digits until a single digit remains.Mathematical optimization using modulo 9 properties can solve this in constant time.TutorialsPoint - Digital Root | Iterative & Recursive Solutions
Asked in
Google 15 Microsoft 12 Amazon 8 Apple 6
23.4K Views
Medium Frequency
~12 min Avg. Time
845 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