原题链接:https://www.acwing.com/problem/content/795/

高精度乘以低精度,只需用高精度的每一位去乘以低精度即可。

高精度x低精度

#include <iostream>
#include <string>
#include <vector>

using namespace std;

// 16
// x 135
// -------------
// | | |9|0|
// | |4|8|
// |1|6|
// _____________
// |2|1|7|0

vector<int> mul(vector<int>& A, int B) {
vector<int> C;
int t = 0; // t表示进位
for (int i = 0; i < A.size(); ++i) {
t = A[i] * B + t;
C.push_back(t % 10);
t /= 10;
}
if (t > 0) C.push_back(t);
// 去除前导0
while (C.size() > 1 && C.back() == 0) C.pop_back();
return C;
}

int main() {
string a; int b;
cin >> a >> b;
vector<int> A;
for (int i = a.length() - 1; i >= 0; --i) A.push_back(a[i] - '0');
vector<int> C = mul(A, b);
for (int i = C.size() - 1; i >= 0; --i) { printf("%d", C[i]); }
return 0;
}

高精度x高精度

高精度乘以高精度,本质上是次乘法(这里是位数),然后相加。

#include <iostream>
#include <vector>

using namespace std;

vector<int> mul(vector<int> &A, vector<int> &B)
{
vector<int> C(A.size() + B.size());

for (int i = 0; i < A.size(); i++)
for (int j = 0; j < B.size(); j++)
C[i + j] += A[i] * B[j];

for (int i = 0, t = 0; i < C.size() || t; i++)
{
t += C[i];
if (i >= C.size()) C.push_back(t % 10);
else C[i] = t % 10;

t /= 10;
}

while (C.size() > 1 && C.back() == 0) C.pop_back();

return C;
}

int main()
{
string a, b;
cin >> a >> b;

vector<int> A, B;
for (int i = a.size() - 1; i >= 0; i--) A.push_back(a[i] - '0');
for (int i = b.size() - 1; i >= 0; i--) B.push_back(b[i] - '0');

vector<int> C = mul(A, B);

for (int i = C.size() - 1; i >= 0; i--) cout << C[i];
puts("");

return 0;
}