Problem Description:
A happy number is a number defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers) (Wikipedia).
For example number 7 is happy because after a number of steps the computed sequence ends up with a 1: 7, 49, 97, 130, 10, 1
while 3 is not, and would give us an infinite sequence: 3, 9, 81, 65, 61, 37, 58, 89, 145, 42, 20, 4, 16,3 7, 58, 89, 145, 42, 20, 4, 16, 37, ...
Write a function that takes n as parameter and return true if and only if n is an happy number.
Happy coding!
My train of thought:
End the loop when sum=1 is obtained (sum=sum of the squares of the current digits). For some numbers that are not happy numbers, this while has to be done all the time, and a flag is set to judge that they are all infinite numbers (Number.POSITIVE_INFINITY), and if so, return false directly. But this still times out.
my answer:
function isHappy(n) { // Good Luck var sum=0; var flag=1; while(sum!=1){ var a=n.toString().split(""); for(var i=0;i<a.length;i++){ sum=sum+Math.pow((+a[i]),2); } n = sum flag+=1; if(flag=="Infinity"){return false;} } return true; }
Excellent answer:
(1) By judging whether n appears in a loop, jump out of the while loop
function isHappy(n) { let arr = [] while (n !== 1 && arr.indexOf(n) === -1) { arr.push(n); n = n.toString().split('').map(x => Math.pow(Number(x), 2)).reduce((p, n) => p + n, 0); } return n ==1?true:false; }
Hahaha!