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