KatInterview

Determine Convergence of Digit-Square Sums

Math & Bit ManipulationAuto-graded · 23 test cases
EasyAuto-gradedMath & Bit Manipulationmathhash-tabletwo-pointers

Last updated

Simulate a transformation that replaces a number with the sum of its squared digits, determining if it terminates at 1 or loops indefinitely.

Given a positive integer n, apply a sequence of transformations where each step replaces the current integer with the sum of the squares of its base-10 digits.

Determine whether this process eventually reduces the number to 1.

Specifically:

  • If the sequence reaches 1, it will remain 1 permanently (1 maps to 1), so return True.
  • If the sequence enters a cycle that does not include 1, it will repeat infinitely, so return False.

Constraints

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

Examples

Example 1

Input: is_happy(7)

Output: True

Example 2

Input: is_happy(2)

Output: False

Example 3

Input: is_happy(1)

Output: True

Hints

Hint 1

Think of the sequence of transformed values as nodes in a directed graph where every node has out-degree 1.

Hint 2

Upper bounds: calculate the maximum possible value after a single transformation step for a 10-digit number. Notice how quickly numbers shrink.

Hint 3

To detect whether a sequence enters an infinite loop, record previously visited numbers in a hash set or use Floyd's tortoise-and-hare cycle-finding algorithm.