A happy number reaches 1 when you repeatedly replace it with the sum of the squares of its digits; otherwise it loops forever (e.g. 19 -> 82 -> 68 -> 100 -> 1).
Repeatedly transform the number into the sum of its squared digits. Because unhappy numbers fall into a cycle, detect repetition with a seen-set (or Floyd's slow/fast on the transform). Stop when you reach 1 (happy) or revisit a number (unhappy). Effectively O(log n) work per step.
public static boolean isHappy(int n) {
Set<Integer> seen = new HashSet<>();
while (n != 1 && !seen.contains(n)) {
seen.add(n);
int sum = 0;
while (n > 0) { int d = n % 10; sum += d * d; n /= 10; }
n = sum;
}
return n == 1;
}function isHappy(n) {
const seen = new Set();
while (n !== 1 && !seen.has(n)) {
seen.add(n);
let sum = 0;
while (n > 0) { const d = n % 10; sum += d * d; n = Math.floor(n / 10); }
n = sum;
}
return n === 1;
}def is_happy(n):
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = sum(int(d) ** 2 for d in str(n))
return n == 1Happy Number is really a cycle-detection problem in disguise — the same technique that catches infinite loops in iterative transforms.
Without cycle detection, an unhappy number loops forever. What are two ways to terminate?