Take a positive whole number and replace it with the sum of the squares of its digits. Do the same to the result, and keep going.
Two things can happen. Either the walk reaches 1, after which it stays at 1 for ever (1² = 1), or it never reaches 1 and goes round the same loop of numbers again and again. A number whose walk reaches 1 is called happy.
Given n, return true if it is happy and false if it is not.
Example 1
Input: n = 23
Output: true
2² + 3² = 13, then 1² + 3² = 10, then 1² + 0² = 1.
Example 2
Input: n = 4
Output: false
The walk goes 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 and then back to 4. It will repeat those eight numbers for ever and never reach 1.
Example 3
Input: n = 1111111
Output: true
Seven ones give 7 after one step. Then 7 → 49 → 97 → 130 → 10 → 1.
Constraints
1 <= n <= 2³¹ - 1The next number depends only on the current one, so once any number comes round a second time the walk is stuck in a loop for ever. The question is whether you reach 1 before anything repeats.
23
true