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 include 1. - Those numbers for which this process ends in 1 are happy. Return true if n is a happy number, and false if not.
Example 1
Input: n = 19
Output: true
Explanation: Square and add the digits repeatedly: 1² + 9² = 82, 8² + 2² = 68, 6² + 8² = 100, and 1² + 0² + 0² = 1. The process reaches 1, so 19 is happy.
Example 2
Input: n = 2
Output: false
Explanation: 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, and then the cycle repeats. It never reaches 1, so 2 is not happy.
Example 3
Input: n = 1
Output: true
Explanation: The number is already 1, so it is happy.
Repeatedly replace n by the sum of the squares of its digits. If you ever reach 1 it's happy; if you revisit a number you've seen before, you're in a cycle that never hits 1, so it's not.
Run checks all cases above. Submit evaluates all test cases.