[LeetCode] 202. Happy Number

Find happiness numbers. If the definition is happy digital numbers on every square of the sum of the last to become one, then this figure is a happy number.

The idea is to do in accordance with its rules of operation, if the last is false, there must be some middle infinite loop, where you can use hashset record and appeared. If the final can be considered as 1, that is true.

 1 /**
 2  * @param {number} n
 3  * @return {boolean}
 4  */
 5 var isHappy = function(n) {
 6     var seen = [];
 7     while (true) {
 8         seen.push(n);
 9         var s = n.toString();
10         n = 0;
11         for (var i = 0; i < s.length; i++) {
12             n += Math.pow(parseInt(s[i]), 2);
13         }
14         if (n === 1) return true;
15         if (seen.includes(n)) return false;
16     }
17 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/11670561.html