“This is the 10th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
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.
The key to this problem is to determine whether the sum of squares is an infinite loop, so we just need to see if the values that appear have occurred before.
So we came up with a hash array for storage.
Var isHappy = function(n) {// Create a hash array let set = new set (); If n=1, or if a loop occurs, the loop ends while(n! = 1 &&! Set.has (n)){// Store the new value to hash set.add(n); N =getNext(n)} return n==1}; Var getNext = function(n){let total = 0; n=n.toString() for(let i=0; i<n.length; i++){ total = total+n[i]*n[i] } return total*1 }Copy the code
If we think of the number n as a single linked list, if there’s a loop then the linked list is a circular linked list, and that’s another problem we wrote earlier, a circular linked list. All we need to do is set up a fast and slow pointer, and if the fast and slow Pointers are equal, then we have a loop.
Var isHappy = function(n) {// let slow = n; let fast = getNext(n); // If the fast pointer ends, or if the fast and slow Pointers are equal, the loop ends while(fast! =1&&fast! =slow){// slow = getNext(slow); GetNext (getNext(fast))} return fast==1}; Var getNext = function(n){n = n.tostring (); let total =0; for(let i = 0; i<n.length; i++){ total = total+n[i]*n[i] } return total*1 }Copy the code