[LC 202] Happy number

Intuitive solution is easy: remember all the numbers that have been reached, as soon as find a number that has appeared before, we find a loop and return false.
Another interesting solution: cycle detection, have two pointers, slow and fast, and fast is going twice faster than the slow pointer. If they meet at one, return true, otherwise, return false.
Code template for cycle detection:
    int fast = start;
    int slow = start;
    do {
        slow = moveForward(slow) ;
        fast = moveForward(fast);
        fast  = moveForward(fast);
    } while(slow != fast);
    if (some condition) return someThing;
    else return otherThings;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s