202. Happy Number ๐คฉ
Last updated
Was this helpful?
Last updated
Was this helpful?
Difficulty: Easy
- Tags: Math
, Hash Table
, Two Pointers
Write an algorithm to determine if a number n
is a happy number.
A happy number is a number defined by the following process:
Start with any positive integer.
Replace the number with 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 that does not include 1
.
If the process ends in 1
, the number is considered happy.
Return true
if n
is a happy number, otherwise return false
.
๐น Example 1:
Input:
Output:
Explanation:
๐น Example 2:
Input:
Output:
1 <= n <= 2^31 - 1
We can use a HashSet
to detect cycles. Alternatively, the two-pointer technique (Floydโs Cycle Detection) can help identify loops.
HashSet for Cycle Detection:
Use a HashSet
to store numbers already seen during the process.
If a number repeats, a cycle is detected, and the process won't reach 1
.
Helper Method (getNext
):
Calculate the sum of the squares of the digits of the current number.
Termination:
Return true
if n
becomes 1
.
Return false
if a cycle is detected.
O(log(n)) per step to calculate the sum of the squares of digits.
In total, the number of steps depends on the cycle length or reaching 1
.
O(log(n)):
For the storage of seen numbers in the HashSet
.
You can find the full solution .