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