A number is called happy if repeatedly replacing it with the sum of the squares of its digits eventually results in 1.
If it enters a cycle that does not include 1, it is not happy.
Your task is to determine whether a number is happy.
Given a number n:
-
Split it into digits
-
Square each digit
-
Take the sum
-
Repeat this process
If the process reaches 1 → happy number
If it cycles → unhappy number
A single integer n
Boolean: true if happy, false otherwise
Example 1
Input:
n = 19
Process:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1
Output:
true
Explanation:
The sequence reaches 1.
Example 2
Input:
n = 2
Process enters a loop (never becomes 1)
Output:
false
- 1 ≤ n ≤ 2³¹ - 1
-
Use a set to detect repeated values (cycle detection).
-
Or use Floyd’s cycle algorithm (slow/fast pointer).
-
The sum of squares operation always reduces the magnitude.
If a number is happy, the chain of "sum of squares of digits" will eventually shrink to 1.
If it ever repeats a value, a cycle has formed → not a happy number.
Using a set:
-
Keep computing sums
-
If a sum repeats → cycle → false
-
If sum becomes 1 → true