“This is the 10th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

[B] [C] [D]

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 you can change it to 1, then that number is happiness.

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

Example 1:

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

Example 2:

Input: n = 2 Output: falseCopy the code

Tip:

  • 1 <= n <= 231 - 1

How do you tell if a number is a happy number, but how do you know if it is not a happy number and has gone into an infinite loop?

Let’s look at 2 adding the sum of the squares of the numbers at each position

2 4 16 37 58 89 145 42 20 4 16 37 58 89 145 42 20 4

And what we found is that when you get a 4, you get 16, 37, 58, 89, 145, 42, 20, until you get to 4 again

To see if the above process is accidental, let’s look at 5 adding the sum of squares of each position number

5 25 29 85 89 145 42 20 4 16 37 58 89 145 42 20 4

It’s still going to be 4, and it’s going to keep going forever

Then we write the following code to solve the problem according to this condition:

var isHappy = function(n) { const s = n+''; let total = 0; for(let i = 0; i<s.length; i++){ total += Math.pow(s[i],2) } if(total === 1) return true; if(total === 4) return false; return isHappy(total) };Copy the code

Once the code is submitted, it’s ok, so we’re done with leetcode-202- happiness number

If you have any questions or suggestions, please leave a comment!