Fast & Slow Pointers
LC #202Easy
Happy Number
Fast & Slow Pointers
AmazonGoogleLinkedInProblem
A happy number eventually reaches 1 under the process of replacing it with the sum of squares of its digits. Detect if a number will cycle forever.
mathhash-setfast-slow-pointers
Constraints
- ›1 ≤ n ≤ 2³¹ − 1
- ›Non-happy numbers cycle (known cycle includes 4, 16, 37, 58, 89, 145, 42, 20)
Example
Input
n = 19Output
trueWhy
19 → 1²+9²=82 → 8²+2²=68 → 6²+8²=100 → 1²+0²+0²=1 ✓