code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

202 Happy Number

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const happyNumber = n => {
  const squareOfDigits = n => {
    let sum = 0
    while (n) {
      r = n % 10
      sum += Math.pow(r, 2)
      n = Math.floor(n / 10)
    }
    return sum
  }
  const set = new Set()
  while (!set.has(n)) {
    set.add(n)
    n = squareOfDigits(n)
    if (n == 1) {
      return true
    }
  }
  return false
}

console.log(happyNumber(19))

Created 2022-03-19T10:55:16+00:00 · Edit