BudiBadu Logo

Happy Number

Hash Table Easy 4 views
Like0

Write an algorithm to determine if a number n is happy.

A happy number is defined by repeatedly replacing the number by the sum of the squares of its digits until it equals 1. If it loops endlessly in a cycle that does not include 1, then it is not happy.

Use a hash set to detect cycles.

Example 1:

Input: n = 19
Output: true

Example 2:

Input: n = 2
Output: false

Example 3:

Input: n = 1
Output: true

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