A happy number is a number where the process of repeatedly replacing the number by the sum of squares of its digits eventually leads to 1.
Example 1:
Input: n = 19
Output: true
Explanation:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1
Use Floyd's cycle detection (slow/fast pointers) or hash set to detect cycles.
1class Solution {
2 public boolean isHappy(int n) {
3 Set<Integer> seen = new HashSet<>();
4 while (n != 1 && !seen.contains(n)) {
5 seen.add(n);
6 n = sumSquares(n);
7 }
8 return n == 1;
9 }
10
11 private int sumSquares(int n) {
12 int sum = 0;
13 while (n > 0) {
14 int digit = n % 10;
15 sum += digit * digit;
16 n /= 10;
17 }
18 return sum;
19 }
20}