Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created April 2, 2020 21:37
Show Gist options
  • Save RP-3/68d85a2a0f5dcf47f798a4297a842bbe to your computer and use it in GitHub Desktop.
Save RP-3/68d85a2a0f5dcf47f798a4297a842bbe to your computer and use it in GitHub Desktop.
/**
* @param {number} n
* @return {boolean}
*/
var isHappy = function(n) {
const seen = new Set();
const next = (n) => {
let sum = 0;
while(n){ // keep popping off the last digit until we get to zero
const r = n%10;
n = Math.floor(n/10);
sum+=Math.pow(n, 2);
}
return sum;
};
while(n !== 1){ // search for cycle
if(seen.has(n)) return false;
seen.add(n);
n = next(n);
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment