easy +8 pts

Happy number check

Determine whether a number is happy by iterating the sum of squares of its digits.

A happy number is a number that eventually reaches 1 when replaced by the sum of the square of each digit repeatedly. If the process enters a cycle that does not include 1, the number is unhappy. Write a function `is_happy(n: int) -> bool` that takes a positive integer `n` and returns `True` if `n` is happy, `False` otherwise. For example, 19 is happy because: - 1^2 + 9^2 = 82 - 8^2 + 2^2 = 68 - 6^2 + 8^2 = 100 - 1^2 + 0^2 + 0^2 = 1 2 is unhappy because it enters the cycle 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.

Constraints

- `n` is a positive integer (1 ≤ n ≤ 10^9) - The function must return a boolean. - Time complexity: O(number of iterations), which is small.

Example

>>> is_happy(19)
True
>>> is_happy(2)
False
>>> is_happy(1)
True
>>> is_happy(7)
True
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a set to remember numbers you have already seen.
While n is not 1 and not in the seen set, add n to the set and replace n with the sum of the squares of its digits.
If you reach 1, return True; if you encounter a number already seen, return False.
Use a helper function to compute the next number from a given number.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.