问题描述:
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!
我的思路:
当求得sum=1时结束循环(sum=当前数各个位的平方之和)。对于有的数不是happy数,这个while就得一直做下去,设置一个flag判断是都为无穷大数(Number.POSITIVE_INFINITY),若是,则直接返回false。但是这样仍然超时。
我的答案:
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; }
优秀答案:
(1)通过判断n是不是循环出现,跳出while循环
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; }
哈哈哈!