82. Cheerful Number

A lottery clerk plays a game with a positive integer n. In each round, the current number is replaced by the sum of the squares of its decimal digits, and the game continues with that new number. Some starting numbers eventually land on exactly 1 and then stay there; such a number is called cheerful. Every other starting number gets stuck in a repeating loop of values that never includes 1, and is called gloomy.

Return true if n is cheerful and false otherwise.

Example 1

Input:
n = 7
Output:
true
Explanation:

7 -> 49 -> 97 -> 130 -> 10 -> 1, so it reaches 1 and is cheerful.

Example 2

Input:
n = 20
Output:
false
Explanation:

20 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20, a loop that never reaches 1.

Constraints

1 ≤ n ≤ 231 - 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(log n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…