Happy Number
Easy · two pointers
Start with a positive integer n and repeat this step: replace the number with the sum of the squares of its decimal digits. For example, 49 becomes 4² + 9² = 16 + 81 = 97, and then 97 becomes 9² + 7² = 130.
Return whether the number eventually becomes 1, as opposed to never getting there. Once a number is 1 it stays 1, because 1² = 1.
Examples
Example 1
Input: n = 19
Output: True
19 becomes 1² + 9² = 82, then 8² + 2² = 68, then 6² + 8² = 100, then 1² + 0² + 0² = 1.
Example 2
Input: n = 2
Output: False
2 becomes 4, then 16, 37, 58, 89, 145, 42, 20 and back to 4, so it circles forever without reaching 1.
Example 3
Input: n = 1
Output: True
The number is already 1.
Constraints
- 1 <= n <= 2^31 - 1