Given a non-negative integer, repeatedly sum its digits until the result is a single digit (0-9). This is also known as the digital root of a number.

For example, given 38:

  • First iteration: 3 + 8 = 11
  • Second iteration: 1 + 1 = 2
  • Result: 2 (single digit achieved)

Method Signature:

public static Integer digitalRoot(Integer num)

Examples:

Example 1:

Input: 38 Output: 2 Explanation: 3 + 8 = 11, then 1 + 1 = 2

Example 2:

Input: 123 Output: 6 Explanation: 1 + 2 + 3 = 6 (already single digit)

Example 3:

Input: 9 Output: 9 Explanation: Already a single digit

Example 4:

Input: 0 Output: 0 Explanation: Zero is a single digit

Example 5:

Input: null Output: null Explanation: Handle null input gracefully
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 October 2026 (Oct 16–31)Sponsored by FLXBL

Contest runs October 16 - 31. Complete challenges to climb the leaderboard!

Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes

Only the 16 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