codejump
EasyPro challengePythonJavaScriptTypeScript

Math — Happy Number

AlgorithmsMathHash SetCycle Detection

Replace a positive integer by the sum of the squares of its digits, and repeat. If the
process reaches 1 the number is happy; otherwise it loops forever in a cycle that
never contains 1.

solve(n) — return true when n (1 <= n < 2^31) is happy.

The sequence cannot grow without bound (a 10-digit number maps to at most 810), so it either
reaches 1 or repeats a value. Detect the repeat with a Set of seen values, or in O(1)
space with Floyd's slow / fast pointers on the "next number" function.

Examples

solve(19)  → true     // 1² + 9² = 82 → 68 → 100 → 1
solve(2)   → false
solve(7)   → true

Sample tests

Test #1Classic happy number
Input: [19]
Output: true
Test #2Falls into the 4 cycle
Input: [2]
Output: false
Test #3One is happy
Input: [1]
Output: true