Hash table exercise [3]

The study arrangement is based on "Code Caprice"~leetcode202

Although the topic is simple, after thinking about it, it is found that there are still difficulties in logic, and a certain observation ability is required.

I can only think of three situations:

1. The calculation result is 1;

2. The calculation results keep looping;

3. The calculation results are infinite

But because I don't know how to write the third situation, I still glanced at the answer.

Through official analysis, we know that the third situation is impossible.

Because from four digits and beyond, the sum of these numbers will always be one less. For example, for a four-digit number, the maximum sum is 324, which is already a three-digit number.

So it is deduced that there is no case of infinity.

After getting this call, it's easy to write.

class Solution {
public:
    bool isHappy(int n) 
    {
        int result=0;
        int m;
        unordered_set<int>s;
        bool t=false;
        while(1)
        {
            while(n>0)
            {
                m=n%10;
                result+=pow(m,2);
                n=n/10;
            }
            if(result==1) 
            {
                t=true;
                break;
            }
            if(s.count(result))
            {
                break;
            }
            else 
            {
                n=result;
                s.insert(result);
            } 
            result=0;
        }
        return t;
    }
};

        Here is the code I wrote and corrected. When I wrote it for the first time, there was a prompt that the time limit was exceeded. At that time, I didn't know why this error occurred. Compared with the official answer and the answer of the code, I found that it was also There is nothing different.

        The answer in the code random record, knowledge encapsulates the calculation result with a function, and also uses two loops.

        So, I can only debug on VS. Later, I found that after I inserted the result in the hash table, I didn't reset the result to 0 in time, which resulted in an error in the result and an infinite loop.

        Summary: The logic of simple questions is not clear and difficult to do; each step of the cycle must be re-checked.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324192364&siteId=291194637