Menu
CoddyTech

Happy Number

Start from a positive integer n and replace it with the sum of the squares of its digits, over and over. For example, 12 becomes 1² + 2² = 5. If this process reaches 1, n is a happy number; otherwise it circles forever through numbers that never include 1. Return true if n is happy and false if it is not.

Function

isHappy(n: integer) → boolean
ninteger
the positive integer to test
Returnsboolean
true if repeating the digit-square sum reaches 1, false if it loops forever

Constraints

  • 1 ≤ n ≤ 231-1

Examples

Input
n = 7
Output
true
Explanation
7 becomes 49, then 4² + 9² = 97, then 130, then 10, then 1. The process reaches 1, so 7 is happy.

lock icon+16 hidden tests on Submit

challenge icon

Follow-up

How would you count the happy numbers from 1 to 10^6 quickly, reusing the answers for numbers below 1000 instead of walking every start from scratch?

Reset code
def isHappy(n):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

n = 7

Expected

true