模板——高精度乘法

#include<string>
#include<iostream>
using namespace std;

const int maxn = 1e6 + 10;

int n, m;
string s1, s2;
int a[maxn], b[maxn], ans[maxn];

void Mul() {
    
    
	for (int i = n - 1, j = 1; i >= 0; i--, j++) {
    
    
		a[j] = s1[i] - '0';
	}
	for (int i = m - 1, j = 1; i >= 0; i--, j++) {
    
    
		b[j] = s2[i] - '0';
	}
	for (int i = 1; i <= n; i++) {
    
    
		for (int j = 1; j <= m; j++) {
    
    
			ans[i + j - 1] += a[i] * b[j];
			ans[i + j] += ans[i + j - 1] / 10;
			ans[i + j - 1] %= 10;
		}
	}
}
int main() {
    
    

	cin >> s1 >> s2;
	n = s1.size(), m = s2.size();

	int cnt = 0;
	if (s1[0] == '-') {
    
    
		cnt++, s1.erase(0, 1), n--;
	}
	if (s2[0] == '-') {
    
    
		cnt++, s2.erase(0, 1), m--;
	}
	Mul();

	int k = n + m;
	if (cnt & 1 && s1 != "0" && s2 != "0") cout << "-";
	while (ans[k] == 0 && k > 1) k--;
	for (int i = k; i >= 1; i--) {
    
    
		cout << ans[i];
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45739057/article/details/105584651