簡単 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 つずつ開いてみましょう。

ヒント 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 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。