Problema
Start with a positive integer and replace it by the sum of the squares of its digits. Keep doing that. If the number eventually becomes 1, the starting number is happy. Otherwise the process falls into a loop that never contains 1, and the number is unhappy. For example, 7 → 49 → 97 → 130 → 10 → 1, so 7 is happy.
Implement happy_number(n).
You need a way to notice that the sequence has started repeating, so the loop stops on unhappy numbers too.
Input
n: The starting number.
Output
Return true if the process reaches 1, otherwise false. The number 1 itself is happy.
Restricciones
1 ≤ n ≤ 10^9
Ejemplos
Entrada:
n = 19
Salida esperada:
expected = True
Entrada:
long long n = 19;
Salida esperada:
bool expected = true;
Entrada:
long n = 19;
Salida esperada:
bool expected = true;
Explicación
1² + 9² = 82, then 8² + 2² = 68, then 6² + 8² = 100, then 1² + 0² + 0² = 1, so 19 is happy: true.
Entrada:
n = 4
Salida esperada:
expected = False
Entrada:
long long n = 4;
Salida esperada:
bool expected = false;
Entrada:
long n = 4;
Salida esperada:
bool expected = false;
Explicación
4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 repeats without ever reaching 1, so the answer is false.
Cómo abordarlo
Inténtalo primero por tu cuenta y luego abre las pistas una a una.
Pista 1
Write a helper that maps a number to the sum of the squares of its digits.
Pista 2
An unhappy number repeats a value it has already produced; remember the values you have seen.
Pista 3
The sequence drops below a few hundred very quickly, so the set stays small.
Complejidad esperada
O(log n) steps per number, O(1) extra space with two pointers
Referencias
Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.