基本原理:将两个数字转换成字符,放到字符数组中。为了防止溢出。
思路:
在计算十进制数 123 * 45 时,首先计算 123 * 5 = 615,然后计算 123 * 4 = 492,最终结果是 615 + 492 * 10 = 5535。
大数乘法的计算过程与此相同:对于A(a0a1a2...an-1) * B(b0b1b2...bm-1),并假设N≥M(被乘数位数不小于乘数时,效率最高),对于B中的每一位 bi,计算其与A的乘积,并在后面补上 i 个零,将结果累加,即为A与B的乘积。
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string num1,num2;
cin>>num1;
cin>>num2;
const char * n1;
const char *n2;
if(num1.size() < num2.size())
{
n1 = num2.c_str();
n2 = num1.c_str();
}
else
{
n1 = num1.c_str();
n2 = num2.c_str();
}
char* n = new char [strlen(n1)+strlen(n2)+1];
for(int i =0; i<strlen(n1)+strlen(n2);i++)
{
n[i] = '0';
}
n[strlen(n1)+strlen(n2)] = '\0';
int count = 0,flag = 0;
for(int i = strlen(n1)-1;i>=0;i--)
{
flag++;
int x1 = n1[i]-'0';
char carry = '0';
for(int j = strlen(n2)-1;j>=0;j--)
{
int x2 = n2[j]-'0';
int sum = x1*x2 + (carry-'0') + n[count] - '0';
n[count++]=(sum%10)+'0';
carry =(sum/10) + '0';
}
if(carry != '0')
{
n[count] = carry;
count=flag;
}
else
count = flag;
}
for(int i = strlen(n)-1;i>=0;i--)
{
if((i==strlen(n)-1)&&(n[i]=='0'))
{
continue;
}
cout<<n[i];
}
cout<<endl;
delete[]n;
return 0;
}