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.
If n is a string and you loop through it by adding the squares of each string and then loop through it if it ends up equal to 1 returns true if it has a happy number if it does not return false if it is not a happy number
The answer
function getNext(num){ let stringNum = num.toString() let resultNum = 0 for(let i = 0; i <stringNum .length; i++) { resultNum += Math.pow(stringNum.charAt(i),2) } return resultNum; } //82 let arr = new Set() let num = 0; while(1){ if(num==0){ num = getNext(n); }else{ num = getNext(num); } if(arr.has(num)) return false; if(num==1) return true; arr.add(num); }};Copy the code