Happy number

Easy TimeO(log n) SpaceO(log n)

Replace a number by the sum of the squares of its digits, and repeat. Some numbers reach 1 and stay there, because 1 maps to itself; every other number falls into a cycle that never contains 1. Given a positive integer n, return true when the repetition starting at n reaches 1 and false when it does not.

Examples

Example 1

Input
n = 19
Output
true
1² + 9² = 82, then 68, then 100, then 1² + 0² + 0² = 1.

Example 2

Input
n = 4
Output
false
4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4, back where it started.

The Code

function digitSquareSum(n) {
  let total = 0;
  while (n > 0) {
    const d = n % 10;
    total += d * d;
    n = Math.floor(n / 10);
  }
  return total;
}
function isHappy(n) {
  const seen = new Set();
  while (n !== 1 && !seen.has(n)) {
    seen.add(n);
    n = digitSquareSum(n);
  }
  return n === 1;
}
isHappy(19);
Done
Step through isHappy(19) call by call