0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

巨大な数のかけ算(文字列処理)

Posted at

最初は BigInt でサクッと終わらせたかったけど、文字列処理がテーマだったので、文字列処理で掛け算をやっていく!


問題概要

数値を表す文字列 S と 1 桁の数値 T が与えられるので、S * T の結果を表す文字列を出力。


入力例:
987654321
9

出力例:

8888888889

https://paiza.jp/works/mondai/string_primer/advance_step12



コード例:(BigInt使用例)

const [A, B] = lines.map(line => BigInt(line));
console.log((A * B).toString());

🌀 楽だけど、これは“反則”!文字列処理がテーマだからNG!



✅OKコード(文字列処理)

const rl = require('readline').createInterface({ input: process.stdin });
const lines = [];

// 入力を配列に貯めておく
rl.on('line', (line) => lines.push(line));

rl.on('close', () => {
    const S = lines[0];     // 文字列としての大きな数
    const T = Number(lines[1]); // 数字(1桁)

    let carry = 0;          // 繰り上がり(最初は0)
    let result = "";        // 答えを作るための文字列

    // 文字列Sの末尾(1の位)から先頭(上位の位)に向かって処理
    for (let i = S.length - 1; i >= 0; i--) {
        const digit = Number(S[i]);   // 現在の桁の数字
        const product = digit * T + carry; // 現在の桁 × T + 前の繰り上がり

        const digitResult = product % 10;  // 1の位がその桁の答え
        carry = Math.floor(product / 10);  // 10の位以上は次の繰り上がり

        result = digitResult + result;     // 桁の答えを先頭に追加
    }

    // 最後に繰り上がりが残っていたら、それを先頭に追加
    if (carry > 0) {
        result = carry + result;
    }

    // 答えを出力
    console.log(result);
});
  1. S の末尾から 1 桁ずつ取り出して、T を掛ける
  2. 前回の繰り上がり(carry)を足す
  3. 1の位を結果に、10の位は次の繰り上がりに
  4. 全部終わったあとも carry が残ってたら、先頭に追加!



気づきメモ

  • Number()で文字→数値に変換(地味に忘れる)
  • 繰り上がりは Math.floor() でOK!
  • 文字列に桁を追加するときは + result(逆順)
  • T === 0 の特別処理を忘れずに!

## まとめ

「桁が多い= BigInt」じゃない!筆算風に組んでいけば、JSでも文字列だけでしっかり掛け算ができるとわかって大満足。



僕の失敗談(´;ω;`)と解決法🐈

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?