Write an algorithm to determine if a number n
is happy.
A happy number is a number defined by the following process:
Return true
if n
is a happy number, and false
if not.
For example:
Example 1:
Input: n = 19 Output: true Explanation: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
Example 2:
Input: n = 2 Output: false
Constraints:
1 <= n <= 231 - 1
# Happy Number
## Problem Description
We are tasked with determining whether a given number `n` is a happy number. A happy number is defined by repeatedly replacing the number by the sum of the squares of its digits. This process continues until either the number becomes 1 (and stays there), or it enters a cycle that doesn't include 1. If the process ends in 1, the number is considered happy. We need to return `true` if `n` is a happy number and `false` otherwise.
For example:
* If `n = 19`, the sequence is:
* 1^2 + 9^2 = 82
* 8^2 + 2^2 = 68
* 6^2 + 8^2 = 100
* 1^2 + 0^2 + 0^2 = 1
Since it ends in 1, 19 is a happy number.
* If `n = 2`, the process would loop endlessly without reaching 1, so 2 is not a happy number.
## Naive Solution
A naive approach involves simulating the process as described and checking if the number becomes 1. If the process continues for too long without reaching 1, we can assume that it's stuck in a cycle and return `false`.
```python
def is_happy_naive(n):
seen = set()
while n != 1:
if n in seen:
return False
seen.add(n)
n = sum(int(digit)**2 for digit in str(n))
return True
The optimal solution is essentially the same as the naive one because there is no better mathematical trick to find the happy number. However, the code can be cleaned up to be more readable.
def is_happy(n):
slow, fast = n, n
while True:
slow = sum_of_squares(slow)
fast = sum_of_squares(sum_of_squares(fast))
if fast == 1:
return True
if slow == fast:
return False
def sum_of_squares(n):
sum = 0
while n:
digit = n % 10
sum += digit ** 2
n //= 10
return sum
The run-time complexity is tricky to analyze precisely. In the worst case, we might have to iterate through several numbers before hitting a cycle or reaching 1. However, it's known that all numbers either become 1 or fall into a cycle with a limited number of elements. Therefore, we can consider it as O(log n) since the number of digits reduces substantially in each iteration.
The space complexity for the naive solution is O(log n) because, in the worst case, we store numbers in a set until we find a cycle or arrive at 1. The number of unique numbers we encounter grows logarithmically with n
.
For the optimal solution, space complexity is O(1) because we only use two variables slow
and fast
.
true
immediately.false
since the problem statement indicates 1 <= n
.