Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-131

Happy Number

Problem

Return True if n is a happy number: repeatedly replace it with the sum of the squares of its digits, and check whether it eventually reaches 1.

Unhappy numbers fall into a cycle, so remember every value seen and stop if one repeats. Return False if the cycle is entered.

Hint

1 is happy by definition; every other happy chain eventually reaches it.

Test cases

case 1
in: [19]
expected: true
case 2
in: [2]
expected: false
case 3
in: [1]
expected: true
case 4
in: [7]
expected: true
case 5
in: [4]
expected: false
Starter codePython
def happy_number(n):
    # Your code here
    pass

5 test cases · run your code against them in the editor