编程语言
首页 > 编程语言> > C++大整数相乘

C++大整数相乘

作者:互联网

此题写了忘,忘了写,网上答案太花里胡哨,故写个简单答案在这里。

#include <bits/stdc++.h>
using namespace std;
//大整数乘法 月经题 
const int MAXSIZE = 1000;
int main()
{
	int a[MAXSIZE]={0};
	int b[MAXSIZE]={0};
	int c[MAXSIZE*2+1] = {0};
	string stra,strb;
	cin >> stra >> strb;
	int t1=1,t2=1;
	
	for(int i=stra.size()-1;i>=0;--i)
		a[t1++] = stra[i]-'0';
	for(int i=strb.size()-1;i>=0;--i)
		b[t2++] = strb[i]-'0';
	
	for(int i=1;i<t2;++i)
		for(int j=1;j<t1;++j)
			c[i+j-1] = c[i+j-1]  + a[j] * b[i];

	for(int i=1;i<t1+t2;++i)
	{
		c[i+1] += c[i] / 10;
		c[i] = c[i] % 10;
	}
	
	int nonzero;
	for(nonzero=t1+t2;;nonzero--)
		if(c[nonzero])
			break;
	while(c[nonzero] != 0)
	{
		c[nonzero+1] = c[nonzero] / 10;
		c[nonzero] = c[nonzero] % 10;
		nonzero++;
	}
	for(int i=nonzero-1;i>=1;--i)
		cout << c[i];
	if(accumulate(c,c+t1+t2,0) == 0)
		cout << 0;
	return 0;	
	
}

标签:int,MAXSIZE,整数,++,相乘,C++,strb,stra,size
来源: https://blog.csdn.net/nerdcfl/article/details/90313116