BudiBadu Logo

Happy Number

Hash Table Easy 9 views
Like0

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

Example 1
Input
n = 19
Output
true
Explanation

19 reaches 1 through repeated square-sum.

Example 2
Input
n = 2
Output
false
Explanation

2 falls into a cycle not including 1.

Example 3
Input
n = 1
Output
true
Explanation

1 is already happy.

Algorithm Flow

Recommendation Algorithm Flow for Happy Number - Budibadu
Recommendation Algorithm Flow for Happy Number - Budibadu

Best Answers

java
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;
    }
}