쉬움 0명 해결 정답률 0%

Happy Number

Decide whether repeatedly summing the squares of the digits of a number reaches 1.

배우게 될 내용

  • Compute the sum of squared digits
  • Detect a repeating sequence with a set or two pointers
  • Stop a loop on either of two conditions

문제

번역본 보기

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

예시

예시 1
입력:
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.

예시 2
입력:
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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

아직 통과한 풀이가 없습니다. 풀어서 1위를 차지하세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.