Compute the digital root of a non-negative integer. The digital root is obtained by repeatedly summing the digits of the number until only a single digit remains. For example, the digital root of 9875 is 2 because 9 + 8 + 7 + 5 = 29, and 2 + 9 = 11, and 1 + 1 = 2. Return null when the input is null or negative.

Examples:

Input: n = 7 Output: 7 Explanation: A single digit is its own digital root. Input: n = 38 Output: 2 Explanation: 3 + 8 = 11, then 1 + 1 = 2. Input: n = 9999 Output: 9 Explanation: 9 + 9 + 9 + 9 = 36, then 3 + 6 = 9. Input: n = 0 Output: 0 Explanation: The digital root of 0 is 0. Input: n = -5 Output: null Explanation: Negative input returns null.
Apex Code Editor

Welcome to Lightning Challenge!

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay July 2026

Contest runs July 1 - 31. Complete challenges to climb the leaderboard!

Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In