freeCodeCamp/curriculum/challenges/japanese/10-coding-interview-prep/rosetta-code/happy-numbers.md

2.4 KiB

id title challengeType forumTopicId dashedName
594810f028c0303b75339ad1 ハッピー数 5 302280 happy-numbers

--description--

ハッピー数 は次のプロセスで定義されます。

任意の正の整数から開始して、その各桁をそれぞれ 2 乗して足した数で置き換え、この数が 1 に等しくなる (1 からは変化しない) か、1を含まないサイクルで無限ループするまでこのプロセスを繰り返します。 このプロセスが1で終わる場合の数字がハッピー数となり、1で終わらない場合はアンハッピー数となります。

--instructions--

数値がハッピー数なら true を返し、そうでない場合は false を返す関数を作成してください。

--hints--

happy は関数とします。

assert(typeof happy === 'function');

happy(1) はブール値を返す必要があります。

assert(typeof happy(1) === 'boolean');

happy(1)trueを返す必要があります。

assert(happy(1));

happy(2)falseを返す必要があります。

assert(!happy(2));

happy(7)trueを返す必要があります。

assert(happy(7));

happy(10)trueを返す必要があります。

assert(happy(10));

happy(13)trueを返す必要があります。

assert(happy(13));

happy(19)trueを返す必要があります。

assert(happy(19));

happy(23)trueを返す必要があります。

assert(happy(23));

happy(28)trueを返す必要があります。

assert(happy(28));

happy(31)trueを返す必要があります。

assert(happy(31));

happy(32)trueを返す必要があります。

assert(happy(32));

happy(33)falseを返す必要があります。

assert(!happy(33));

--seed--

--seed-contents--

function happy(number) {

}

--solutions--

function happy (number) {
  let m;
  let digit;
  const cycle = [];

  while (number !== 1 && cycle[number] !== true) {
    cycle[number] = true;
    m = 0;
    while (number > 0) {
      digit = number % 10;
      m += Math.pow(digit, 2);
      number = (number - digit) / 10;
    }
    number = m;
  }
  return (number === 1);
}