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!
Create an Account
Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.
Create accountHow 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 Mar 2026
Contest runs March 3 - 31. Complete challenges to climb the leaderboard!
Points are calculated for challenges completed during the contest period.