var isHappy = function(n) { let nArr = [] // 建立一个用于存放数字的平方和的数组 while(!nArr.includes(n)){ // 如果数组中出现过了算出的平方和 则说明进入循环 跳出 const sum = getSum(n) nArr.push(n) n = sum } return n ==1 }; var getSum = function (n){ let sum = 0 while(n){ sum += (n%10)*(n%10) n = Math.floor(n/10) } return sum }
通过换下链表的方式解题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var isHappy = function(n) { if(!n) returnfalse let slow = n let fast = next(n) while(slow!=fast){ slow = next(slow) fast = next(next(fast)) } return fast==1 }; var next = function (n){ let sum = 0 while(n){ sum += (n%10)*(n%10) n = Math.floor(n/10) } return sum }