Determine whether repeatedly replacing a number with the sum of the squares of its digits eventually reaches 1.
Happy Number
Given a positive integer n, repeatedly transform it by replacing the number with the sum of the squares of its decimal digits.
A number is called happy if this process eventually reaches 1. If the process enters a cycle that does not include 1, the number is unhappy.
Return whether the given number is happy.
Input Format
- A single integer
n. - You may assume
n > 0.
Output Format
- Return
trueifnis a happy number. - Otherwise, return
false.
Constraints
1 <= n- The number may be transformed repeatedly until it reaches
1or a cycle is detected.
Example 1
Input
n = 19
Output
true
Explanation
19 -> ^2 = 82 -> ^2 = 68 -> ^2 = 65 -> 61 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 ... The process eventually reaches a cycle that does not include 1, so 19 is not happy? Wait, this example should be the classic happy-number example. Correct sequence: 19 -> 82 -> 68 -> 100 -> 1. The number 19 is happy.
Example 2
Input
n = 2
Output
false
Explanation
2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 ... The sequence repeats without reaching 1.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.