C++中表示為字串的大數乘法


給定兩個以字串格式表示的數字。我們需要將它們相乘。解決這個問題的思路是維護前一位數字乘法的結果和進位。我們可以使用前一位數字乘法的結果和進位來獲得下一組數字的乘法結果。

讓我們來看一個例子。

輸入

15
2

輸出

30

演算法

  • 將數字初始化為字串。

  • 初始化長度為 **number_one_length + number_two_length** 的字串。

  • 從末尾迭代第一個數字。

    • 從末尾迭代第二個數字。

      • 將兩位數字相乘,並加上對應的上一行數字。

      • 更新上一行數字。

      • 將進位儲存在結果字串的前面索引中。

  • 透過向結果中的每個字元新增 **0** 字元來將字元轉換為數字。

  • 忽略前導零返回結果。

實現

以下是上述演算法在 C++ 中的實現

#include <bits/stdc++.h>
using namespace std;
string multiplyTwoNumbers(string num1, string num2) {
   if (num1 == "0" || num2 == "0") {
      return "0";
   }
   string product(num1.size() + num2.size(), 0);
   for (int i = num1.size() - 1; i >= 0; i--) {
      for (int j = num2.size() - 1; j >= 0; j--) {
            int n = (num1[i] - '0') * (num2[j] - '0') + product[i + j + 1];
            product[i + j + 1] = n % 10;
            product[i + j] += n / 10;
      }
   }
   for (int i = 0; i < product.size(); i++) {
      product[i] += '0';
   }
   if (product[0] == '0') {
      return product.substr(1);
   }
   return product;
}
int main() {
   string num1 = "34";
   string num2 = "57";
   if((num1.at(0) == '-' || num2.at(0) == '-') && (num1.at(0) != '-' || num2.at(0) != '-')) {
      cout << "-";
   }
   if(num1.at(0) == '-') {
      num1 = num1.substr(1);
   }
   if(num2.at(0) == '-') {
      num2 = num2.substr(1);
   }
   cout << multiplyTwoNumbers(num1, num2) << endl;
   return 0;
}

輸出

如果執行上面的程式碼,則會得到以下結果。

1938

更新於:2021年10月25日

4K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.