A happy number is defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number either equals 1 (which means the number is happy) or it loops endlessly in a cycle that does not include 1 (which means the number is not happy).
Write a method isHappyNumber that takes an Integer parameter and returns true if the number is happy, false otherwise. Return false for null, zero, or negative numbers.
Examples:
Input: num = 19
Output: true
Explanation: 1^2 + 9^2 = 82, 8^2 + 2^2 = 68, 6^2 + 8^2 = 100, 1^2 + 0^2 + 0^2 = 1
Input: num = 7
Output: true
Explanation: 7^2 = 49, 4^2 + 9^2 = 97, continues until reaching 1
Input: num = 2
Output: false
Explanation: Number enters a cycle that does not include 1
Input: num = null
Output: false
Explanation: Null input returns false
Input: num = -5
Output: false
Explanation: Negative numbers return false
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 August 2026
Contest runs August 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.