kostumブログ

勉強したことやノート代わりのアウトプットに使っています。

project Euler 016

環境

問題

215 = 32768 であり, 各位の数字の和は 3 + 2 + 7 + 6 + 8 = 26 となる. 同様にして, 21000 の各位の数字の和を求めよ.

考え方

  1. 21000を計算する(bigint型)。
  2. 計算結果の各位の数字を取り出す
  3. 和を計算する

コード

let two = BigInt(2);
let ruijousu = 1000;
let result = BigInt(1);
for (let i = 1; i <= ruijousu; i++) {
  result = result * two;
}
let resultStr = String(result);
let resultList = [];
for (let j = 0; j < resultStr.length; j++) {
  resultList.push(resultStr.charAt(j));
}
let sum = 0;
resultList.forEach(result => {
  sum = sum + Number.parseInt(result);
});
return sum;

説明

  • 21000を計算する(number型では計算できないため、bigint型を使う)
  • 計算結果を文字列に変換し、各位の数を取り出す
  • 取り出した文字を数字に再変換し、和を計算する