Happy Number
Part of Practice: Matrix Choreography
Repeatedly replace a positive integer with the sum of the squares of its digits. A number is "happy" if this process eventually reaches 1 (and then stays there forever). If instead the process falls into an endless loop that never touches 1, the number is not happy. Given n, return whether it is happy.
The hidden question: how do you detect "endless loop" with a finite algorithm? That makes this a cycle-detection problem wearing a math costume.
Examples
- Input:
- n = 19
- Output:
- true
1² + 9² = 82 → 8² + 2² = 68 → 6² + 8² = 100 → 1² + 0² + 0² = 1. Reached 1, so 19 is happy.
- Input:
- n = 2
- Output:
- false
2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 — back at 4, an endless loop that never contains 1.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.