Make writing a habit together! This is the 9th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

I. Problem description

Write an algorithm to determine whether a number n is a happy number.

Happiness number is defined as:

  • For a positive integer, replace the number each time with the sum of squares of the numbers at each of its positions.
  • And then you repeat the process until the number is 1, or it could go on forever but it never gets to 1.
  • If the result of this process is 1, then this number is happiness number.

Return true if n is the happy number; If not, return false.

Happiness number.

Two, the title requirements

The sample

Input: n = 19 Output: true Description: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1Copy the code

inspection

1. Mathematical ideas 2. The recommended time is 15 to 35 minutesCopy the code

Third, problem analysis

The happiness number is easy to understand, just by adding the squares of the split digits. So we need to have a final condition here, which is that it has to be a 2-digit number.

When n is in the range of 1 to 9, the number of digits is added. The final unit number has to be 1 or 7 to end the cycle as a happiness number.

Such as the circular flow of 7: 49 = 42 + 72 = 92 = 97 = 92 + 72 = 130 = 12 + 32 + 10 = 0 = 17 ^ 49 = 4 ^ 2 + 2 = 9 ^ 2 = 97 = 9 7 ^ ^ 2 + 2 = 130 = 1 ^ 2 + 3 ^ 2 + 10 = 0 = = 97 = 172 = = 42 + 49 92 92 + 72 = 130 = 12 + 32 + 10 = 0 = 1

Other numbers, for the time being called unhappy numbers, will enter a loop of 4→16→37→58→89→145→42→20→44 →16→37→58→89→145→ 20→ 20→ 20→ 20→ 20→ 20→ 20→ 20→ 20→44 →16→37→58→89→145→42→20→4. And so on.

Four, coding implementation

class Solution {
public:
    bool isHappy(int n) {
        int k,ans;// Initialize the definition
        while(n>9)// Exit the unit number directly
        {
            k=n;/ / the staging
            ans=0;// Store the result of adding the squares of bits
            while(k)
            {
                ans+=(k%10)*(k%10);// Add the squares
                k=k/10;
            }
            n=ans;
        }
        if(n==1||n==7)//1 or 7, print true
            return true;
        else
            return false; }};Copy the code

V. Test results