Skip to content
Onsite

Happy Number

EasyP2Coding

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

Return true if n is happy, otherwise false.

Example 1

Input
n = 19
Output
true
Why
1^2 + 9^2 = 82, then 68, then 100, then 1.

Example 2

Input
n = 2
Output
false
Why
2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4, a cycle without 1.

Example 3

Input
n = 1
Output
true

Constraints

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

Hints

Run checks the 3 visible tests, Submit all 10.