Intermediate Level

Implement the isHappyNumber method that checks whether repeatedly summing the squares of digits reaches 1.

The input contains an integer n. Your task is to check whether n is a happy number.

A happy number eventually becomes 1 when it is repeatedly replaced by the sum of the squares of its digits. If the process enters a cycle that never reaches 1, the number is not happy. For example, 19 is happy.

Example 1
Input:
n (int) = 19
Return:
(boolean) true
Example 2
Input:
n (int) = 2
Return:
(boolean) false
Example 3
Input:
n (int) = 1
Return:
(boolean) true

Repeat the digit-square-sum process and keep track of numbers already seen.

If the current number becomes 1, return true. If the same number appears again, the process is stuck in a cycle, so return false.

Pseudocode:

function isHappyNumber(n):
    seen = empty set
    while n != 1 and n is not in seen:
        add n to seen
        n = sumOfDigitSquares(n)
    return n == 1
function sumOfDigitSquares(n):
    sum = 0
    while n > 0:
        digit = n % 10
        sum = sum + digit * digit
        n = n / 10
    return sum
Run your code to see the result.