Skip to content

Happy Number

EasyBit Manipulation & Math
Decode it first. Clues, constraints, pattern and plan before any code.

Start with a positive integer n and repeatedly replace it with the sum of the squares of its digits. If this process reaches 1, the number is happy. Otherwise it loops forever in a cycle that never includes 1. Return true if n is happy.

n = 19  →  true    (1 + 81 = 82, 64 + 4 = 68, 36 + 64 = 100, 1 + 0 + 0 = 1)
n = 2   →  false   (2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 → ...)

Constraints

  • 1 <= n <= 2^31 - 1