Created
April 2, 2020 21:37
-
-
Save RP-3/68d85a2a0f5dcf47f798a4297a842bbe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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