Happy Number
Can a number actually be "happy"? In the world of algorithms, the answer is a resounding yes! A number is considered Happy if, when you repeatedly replace it with the sum of the squares of its digits, you eventually land on 1. But be careful—some numbers are destined to loop endlessly in a "unhappy" cycle, never reaching that peaceful 1.
The "secret sauce" here is a Hash Set for cycle detection. Think of it like a breadcrumb trail. As you calculate each new sum, you check your Set: "Have I been to this number before?" If you hit a number that’s already in your Set, you know you’re stuck in an infinite loop and the number is officially unhappy. If you reach 1, you’ve found happiness!
This challenge is a brilliant way to practice using Sets to prevent infinite loops. It turns a mathematical puzzle into a clean, searchable logic problem that's both fast and elegant to solve.
Examples
19 reaches 1 through repeated square-sum.
2 falls into a cycle not including 1.
1 is already happy.
Algorithm Flow

Best Answers
import java.util.*;
class Solution {
public boolean happy_number(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
int total = 0;
while (n > 0) {
int d = n % 10;
total += d * d;
n /= 10;
}
n = total;
}
return n == 1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
