Skip to content
AI360Xpert
Back to Math & Geometry
Easy

Happy Number

Write an algorithm to determine if a number `n` is happy. A happy number is a number defined by the following process: - Starting with any positive integer, replace the number by the sum of the squares of its digits. - Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. - Those numbers for which this process ends in 1 are happy. Return `true` if `n` is a happy number, and `false` if not.

Examples

Input:n = 19
Output:true
1^2 + 9^2 = 82 8^2 + 2^2 = 68 6^2 + 8^2 = 100 1^2 + 0^2 + 0^2 = 1
Input:n = 2
Output:false
2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> ... (cycle detected)

Constraints

  • 1 <= n <= 2^31 - 1

HashSet for Cycle Detection

Approach

We repeatedly calculate the sum of the squares of the digits of `n`. We can use a HashSet to keep track of the numbers we have seen so far. If we reach 1, the number is happy. If we calculate a number that is already in the HashSet, it means we are stuck in a cycle, so the number is not happy and we return false.

Complexity Analysis

Time Complexity
O(log n)
Space Complexity
O(log n)

The number of digits in a number `n` is given by `log10(n)`. We process each digit, and the size of the HashSet grows logarithmically with the input number.

Solution.java
class Solution {    public boolean isHappy(int n) {        Set<Integer> visited = new HashSet<>();                while (!visited.contains(n)) {            visited.add(n);            n = getSumOfSquares(n);            if (n == 1) {                return true;            }        }                return false;    }        private int getSumOfSquares(int n) {        int sum = 0;        while (n > 0) {            int digit = n % 10;            sum += digit * digit;            n = n / 10;        }        return sum;    }}