Code Logo

Happy Number

Published at16 Mar 2026
Easy 13 views
Like0

A number is called happy if repeatedly replacing it with the sum of the squares of its digits eventually leads to 1.

So you do the same transformation again and again: split the number into digits, square each digit, add those squares, and use that new total as the next number. If the process reaches 1, return true. If it falls into a repeating loop that never reaches 1, return false.

For example, 19 is happy because its chain eventually reaches 1. But 2 is not happy because it keeps cycling through other values forever.

So the real task is not just doing the digit math once. It is detecting whether that repeated process ends at 1 or gets stuck in a loop.

Example Input & Output

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
Recommendation Algorithm Flow for Happy Number

Solution Approach

A hash set is very useful here because the hard part is detecting a loop. Every time we transform the number into the sum of the squares of its digits, we get a new state. If we ever see the same state again, then the process is cycling and will never suddenly reach 1 later.

So the plan has two small pieces. First, write a helper that computes the next number. For example, if the current value is 19, the helper should calculate 1^2 + 9^2 = 82. Second, keep a set of all numbers we have already seen during the process.

The loop can be written like this:

const seen = new Set(); while (n !== 1 && !seen.has(n)) { seen.add(n); n = nextValue(n); } return n === 1;

If the loop stops because n === 1, the number is happy. If it stops because seen.has(n) becomes true, we found a repeated state, so the process is trapped in a cycle.

This approach is easy to reason about because the set gives us direct proof that we are looping. The number of distinct states stays small in practice, so the method is efficient and works comfortably within typical constraints.

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