Happy Number

Easy#202cycle

Take a positive number and replace it with the sum of the squares of its digits, again and again. The number is happy if this gets to 1, and not happy if it goes round and round without ever reaching 1. Return whether n is happy. Our example: n = 7, which goes 7 → 49 → 97 → 130 → 10 → 1 — the answer is true.

input
n: a positive integer.
returns
true if n is happy: replacing it with the sum of the squares of its digits, again and again, reaches 1. false if this loops forever without 1, as 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 does.
constraints
  • 1 ≤ n ≤ 2³¹ − 1
our 15 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number} n
 * @return {boolean}
 */
function isHappy(n) {

}
Ctrl ↵
format
reset

saved in this browser

15 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more fast and slow pointers problems

Pattern “Fast and slow pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.