Write an algorithm to determine if a number n is happy.
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.
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.
Return true if n is a happy number, and false if not.
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Input: n = 2
Output: false
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
/*
이전에 나왔던 숫자가 반복되면 loop인걸 확인할수 있음
*/
let map=new Map();
for(; map.get(n)==null; ){
map.set(n,1);
let number=n;
let tempSum=0;
for(; number>0; ){
let rest= number%10;
tempSum=tempSum+Math.pow(rest,2);
// tempSum=tempSum+ (rest*rest)
number=(number/10)>>0; //10으로 나눈 몫에 비트연산으로 소수점 절사
}
if(tempSum==1){
return true;
}
n=tempSum;
}
return false;
};
~.~