Description
Write an algorithm to determine if a number n is happy. A happy number is defined by: Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat until the number equals 1 (where it will stay), or it loops endlessly. Return true if n is a happy number, false otherwise.
Examples
Input:
n = 19Output:
trueExplanation:
1² + 9² = 82, 8² + 2² = 68, 6² + 8² = 100, 1² + 0² + 0² = 1
Input:
n = 2Output:
falseExplanation:
2 leads to an infinite cycle that never reaches 1.
Input:
n = 7Output:
trueExplanation:
7 -> 49 -> 97 -> 130 -> 10 -> 1. The chain reaches 1, so 7 is a happy number.
Constraints
- •
1 ≤ n ≤ 2³¹ - 1