Happy Number
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
trueifnis happy: replacing it with the sum of the squares of its digits, again and again, reaches1.falseif this loops forever without1, as4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4does.- constraints
- 1 ≤ n ≤ 2³¹ − 1
- 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
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more fast and slow pointers problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.