[Algorithm - Double Pointer] LeetCode 202 Happy Number

Topic description: 

Idea: fast and slow pointers

        When I saw the loop, I remembered the method of fast and slow pointers. From the title, we can see that we need to simulate a process: continuously use the current number to generate the next number. The generation rule is to accumulate the squares of the current number; The result is either 1, then the initial number is a happy number; or it is an infinite loop.

        The key is that we cannot let the program loop indefinitely, but we have to determine when it will fall into an infinite loop. If the newly generated number has already appeared, it will inevitably fall into a loop in the generation process of these numbers, such as Example 2:

        After entering the loop, we can use the idea of ​​"fast and slow pointers" to find out the loop: the "slow pointer" takes one step each time, and the "fast pointer" takes two steps each time. When the two are equal, it is a cycle. Finally, determine whether it is a cycle caused by 1. If so, it is a happy number, otherwise it is not a happy number.

Code:

class Solution {
    int NextN(int n)    //返回n这个数每一位上的平方和(即这个数的下一位)
    {
        int sum = 0;
        while(n != 0)
        {
            int t = n % 10;
            sum += t * t;
            n /= 10;
        }
        return sum;
    }
public:
    bool isHappy(int n) {
        int slow = n;
        int fast = NextN(n);
        while(slow != fast)
        {
            slow = NextN(slow);
            fast = NextN(NextN(fast));
        }
        return slow == 1;
    }
};

result:

Guess you like

Origin blog.csdn.net/weixin_44906102/article/details/132287031