高精度乘法:高精度乘以高精度
题目描述
高精度乘法。输入两个正整数,求它们的积。
输入
两行,每行为一个高精度整数,长度不超过255。
输出
一行,相乘的结果。
做题一定要注意边界情况。
#include<stdio.h>
#include<string.h>
using namespace std;
char str1[265];
char str2[265];
int d1[265];
int d2[265];
int result[600];
int size=0;
int main()
{
scanf("%s",str1);
scanf("%s",str2);
int L1=strlen(str1);
int L2=strlen(str2);
//尤其注意边界情况
//输入有0只能输出0
if(L1==1&&str1[0]=='0')
{
printf("0\n");
return 0;
}
if(L2==1&&str2[0]=='0')
{
printf("0\n");
return 0;
}
//首先倒叙高精度数,因为执行四则元算时候是从数字的低位开始运算的
//但是显示在计算机屏幕上的时候 第一位是最高位 所以在存储高精度数的时候 我们需要倒置高精度数
for(int i=L1-1;i>-1;i--)
{
d1[L1-1-i]=str1[i]-'0';
}
for(int i=L2-1;i>-1;i--)
{
d2[L2-1-i]=str2[i]-'0';
}
int c=0;
int temp=0;
for(int i=0;i<L1;i++)
{
for(int j=0;j<L2;j++)
{
result[i+j]+=d1[i]*d2[j];
}
}
for(int i=0;i<L1+L2;i++)
{
c=result[i]/10;
result[i]%=10;
result[i+1]+=c;
}
for(int i=L1+L2-1;i>-1;i--)
{
if(i==L1+L2-1)
{
if(result[i]!=0)
printf("%d",result[i]);
}
else
{
printf("%d",result[i]);
}
}
}