Happy Number - Problem
Write an algorithm to determine if a number n is happy.
A happy number is a number 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 equals
1(where it will stay), or it loops endlessly in a cycle which does not include1. - Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.
Input & Output
Example 1 — Happy Number
$
Input:
n = 19
›
Output:
true
💡 Note:
19 → 1² + 9² = 82 → 8² + 2² = 68 → 6² + 8² = 100 → 1² + 0² + 0² = 1. Since we reached 1, 19 is a happy number.
Example 2 — Unhappy Number
$
Input:
n = 2
›
Output:
false
💡 Note:
2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. We detect a cycle that doesn't include 1, so 2 is not happy.
Example 3 — Single Digit Happy
$
Input:
n = 1
›
Output:
true
💡 Note:
1 → 1² = 1. Already at 1, so it's happy by definition.
Constraints
- 1 ≤ n ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Start with positive integer n
2
Transform
Replace with sum of squares of digits
3
Check
Reaches 1 (happy) or cycles (unhappy)
Key Takeaway
🎯 Key Insight: Every number either reaches 1 (happy) or enters an infinite cycle (unhappy)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code