문제
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.
제약 조건
1 ≤ n ≤ 10^9
예시
입력:
n = 19
예상 출력:
expected = True
입력:
long long n = 19;
예상 출력:
bool expected = true;
입력:
long n = 19;
예상 출력:
bool expected = true;
설명
1² + 9² = 82, then 8² + 2² = 68, then 6² + 8² = 100, then 1² + 0² + 0² = 1, so 19 is happy: true.
입력:
n = 4
예상 출력:
expected = False
입력:
long long n = 4;
예상 출력:
bool expected = false;
입력:
long n = 4;
예상 출력:
bool expected = false;
설명
4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 repeats without ever reaching 1, so the answer is false.
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
Write a helper that maps a number to the sum of the squares of its digits.
힌트 2
An unhappy number repeats a value it has already produced; remember the values you have seen.
힌트 3
The sequence drops below a few hundred very quickly, so the set stays small.
예상 복잡도
O(log n) steps per number, O(1) extra space with two pointers
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.