This is the 8th day of my participation in the First Challenge 2022

Shenzhen picked the star today, very happy, then make a happy number, ha ha ~

Companies

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: n = 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
Copy the code

After looking at the example we drew a picture

Whether very familiar with, this is not a circular linked list, different is add a square sum That we first calculate the number of each value, first to think about, if the digits only one For example, we use 2% 10 = 2 by calculating remainder method to calculate the single digits, if the number is two, three or even more?

I don’t know what happened for a while, but when we had the units digit, we just kept counting units, and when we were done with each digit we divided it by ten and we dropped it, and then we kept going until it was less than zero and then we terminated the loop getNext

Now let’s look at the difficulty, since this is the fast or slow pointer, what are the conditions for our termination?

  1. The value of the fast pointer is equal to that of the slow pointer
  2. The value of the fast pointer is 1

solution

/** @lc app=leetcode.cn id=202 lang=javascript ** [202] happy number */ / @lc code=start /** * @param {number} n * @return {boolean} */ var isHappy = function (n) { let last = n let first = getNext(n) while (first ! = last && first ! = 1) { first = getNext(getNext(first)) last = getNext(last) } return first == 1 }; Var getNext = (n) => {let res = 0 // square of units while (n > 0) {res += (n % 10) * (n % 10) n = math.floor (n / 10)} return  res } // @lc code=endCopy the code