easyMath / GeometryPure DSA~14 min
Retry Loop Detect
A toy backoff scheme repeatedly replaces a retry counter with the sum of the squares of its digits. Some starting counters eventually settle at 1 (the retry succeeds); others spin forever in a cycle. Decide which fate a given start meets.
Problem
Starting from a positive integer n, repeatedly replace it with the sum of the squares of its digits. Return true if the process reaches 1, false if it loops endlessly.
Input
A single integer n (1 ≤ n ≤ 2^31 - 1).
Output
A boolean — true if n reaches 1.
Constraints
- 1 ≤ n ≤ 2^31 - 1
- The sequence either reaches 1 or enters a cycle
- Use O(1) extra space if possible
Examples
Example 1
Input
n = 19
Output
true
1²+9²=82 → 8²+2²=68 → 6²+8²=100 → 1²+0²+0²=1.
Example 2
Input
n = 2
Output
false
2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, which cycles without ever reaching 1.