LeetCode202--Happy Number

Title description : Write an algorithm to determine whether a number is a "happy number".

A "happy number" is defined as: For a positive integer, replace the number with the sum of the squares of the numbers in each position every time, and then repeat this process until the number becomes 1, or it may be an infinite loop but always changes Less than 1. If it can be changed to 1, then this number is a happy number.
Example:
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1


When I wrote this question, I rushed to apply the hash table I just learned. When I first saw this question, I was always thinking about how to exit the loop. If it changed to less than 1, I went to the comment section. Then someone said about the double pointer method, but I didn't know why. Because I think this is a problem marked by a hash table, but a lot of problems have been solved and there is no way to implement a hash table in C language. So I wanted to come back to this double pointer method, what does it mean? What is a double pointer, and under what circumstances did you learn it by yourself? Yes, when solving the circular linked list, isn't there a circular loop at this time? So use this method.
Code :

//计算每个数平方和函数--返回一次计算结果
int sum(int key)
{
    int mod;
    int sum = 0;
    while(key)
    {
        mod = key % 10;
        sum += mod * mod;
        key /= 10;
    }
    return sum;
}

bool isHappy(int n){
    int slow = n;		//慢指针
    int fast = n;		//快指针	
    do{
        slow = sum(slow);		//慢指针走1部
        fast = sum(fast);			/./快指针走两步
        fast = sum(fast);
        if(fast == 1)			//判断快指针的效率会更高一点
            return true;
    }while(slow != fast);
   return false;
}

Thinking: Although I have figured out how to use double pointers, but in terms of code, the code I tried for the first time took too long to run. The idea was correct, but the code was too verbose, so I checked other people’s Double pointer method, useful functions, whether there are functions, but they are very concise! And I have learned the dual pointer but still haven't applied what I learned!

Guess you like

Origin blog.csdn.net/weixin_44184990/article/details/101457213