Happy Number: the idea to remember.
Repeatedly replace a positive integer with the sum of its squared decimal digits; decide whether it reaches one.
The core insight
Track generated values until reaching one or repeating a previously seen state.
Why it works
The digit square sequence eventually repeats within a finite bounded range; a repeated nonone state can never reach one later.
The mistake to avoid
Reset the digit square sum for each replacement rather than accumulating across rounds.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
// Java reference adapted from neetcode-gh/leetcode (MIT).
// Track generated values until reaching one or repeating a previously seen state.
public boolean isHappy(int n) {
if (n == 1 || n == -1) {
return true;
}
Set<Integer> visit = new HashSet<Integer>();
while (!visit.contains(n)) {
visit.add(n);
n = sumOfSquare(n);
if (n == 1) return true;
}
return false;
}
public int sumOfSquare(int n) {
int output = 0;
while (n != 0) {
int digit = n % 10;
digit = digit * digit;
output += digit;
n = n / 10;
}
return output;
}Java reference adapted from neetcode-gh/leetcode · MIT license
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.