Katkat

Decide Whether Repeatedly Summing Squared Digits Reaches 1

SnowflakeSoftware Engineer · Technical Screen

Last updated

Starting from a positive integer, repeatedly replace it by the sum of the squares of its digits and decide whether the sequence reaches 1 or falls into a cycle. It tests cycle detection on an implicit sequence and reasoning about why the values stay bounded.

Starting from a positive integer, repeatedly replace the number by the sum of the squares of its decimal digits. Return whether this process eventually reaches 1.

Function Signature

def is_happy(n: int) -> bool:

Rules

  • One step replaces the current number by the sum of the squares of its digits; for example, 82 becomes 8 * 8 + 2 * 2 = 68.
  • Return True if the number becomes 1 after zero or more steps, so n = 1 itself returns True.
  • Otherwise the numbers eventually repeat in a cycle that never contains 1; return False.

Constraints

  • 1 <= n <= 2^31 - 1

Examples

Example 1

Input: n = 7
Output: True

7 → 49 → 97 → 130 → 10 → 1.

Example 2

Input: n = 2
Output: False

2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, and the cycle starting at 4 repeats forever without reaching 1.

Example 3

Input: n = 1
Output: True

The number is already 1, so no step is needed.