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; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
如果运行上面的代码,则会得到以下结果。
1938
广告