Back to questions
Given an integer , check if it is a looping number. A looping number has the following properties:
Return if is a looping number, otherwise return .
Input:
Output:
Explanation:
Since the number loops back to , it is a looping number.
Input:
Output:
Explanation:
Since the number reaches , it is not a looping number.
The main idea of this approach is that if we reach a number (other than ) that we have seen before, it means the given number forms a loop.
For example, in the second example:
On the other hand, if the number eventually becomes , then there is no loop.
To check if a number appears more than once, we can use a set for quick lookup.
Next, we need to compute the next number in the sequence. There are two ways to do this:
Here’s the string-based approach:
Here’s the modulo-based approach (more efficient):
Here's the full implementation using the second (modulo-based) method to compute the next number:
The Tortoise and Hare Algorithm is a loop detection technique that uses two pointers moving at different speeds:
If a loop exists, the two pointers will eventually meet at some point. Otherwise, if the fast pointer reaches , it means there is no loop, and we return .
In this problem:
If you're not familiar with the Tortoise and Hare Algorithm, you can read more here.
Here's the code: