leetcode 202. Happy Number memory usage better than 100% JavaScript

Posted on

What the problem is asking for is

  • look at each digit separately
  • square the digit
  • sum all the squares
  • if the sum of the squares will eventually equal 1, its a happy number

To solve this problem you have to know a mathematical trick, else the loop will go on forever. Once n < 10, if n is 1 or 7 the number will be happy. Any other number will cause an infinite loop.

var isHappy = function(n) {
    if(n<10){
        if(n===1 || n===7){return true}
        return false
    }
    let sum = 0
    while(n>0){
        let value = n % 10
        sum += value**2
        n -= value
        n /= 10
    }
    if(sum ===1){return true} //I could leave this out...
    return isHappy(sum)
};

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s