Leetcode 202. Happy Number
We use a map the keep records of all the numbers during the process. If at any time the converted number equals to 1 we return true directly, otherwise if the number appeared earlier we return false instead.
Solution
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
let map = {}
const convert = (s) => {
let result = 0
for(let i = 0; i < s.length; i++) {
result += Math.pow(parseInt(s[i]), 2);
}
return result
}
let next = n;
while(1) {
next = convert(next.toString());
if(next === 1) {
return true
} else if(map[next]) {
return false
} else {
map[next] = true
}
}
};