Write an algorithm to determine if a number n is happy. A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits. Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy.
Output: true
Explanation: 1² + 9² = 82 → 8² + 2² = 68 → 6² + 8² = 100 → 1² + 0² + 0² = 1
Output: false
Explanation: The process eventually enters a cycle: 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 ...
Use Floyd's cycle detection (slow and fast pointers) on the sequence of digit-square sums. If the sequence reaches 1, the number is happy. If slow meets fast (cycle detected), it is not happy.
- Define a helper
sumOfSquares(n)that computes sum of squares of digits. - Move slow one step and fast two steps at a time.
- If fast reaches 1, return
true. - If slow equals fast (cycle), return
false.
Complexity Analysis:
Time complexity: O(log n) per step, O(log n) steps — effectively O(log² n) overall.
Space complexity: O(1) — Floyd's cycle detection uses constant space.