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
Returns (boolean) true

Example 2

Input
n (int) = 2
Returns (boolean) false

Example 3

Input
n (int) = 1
Returns (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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.