编程俱乐部每日一练(2018年12月3日)A * B Problem大数乘法
A * B Problem
Description
Now Give you two integers A and B , please caculate the value of A multiply B.Attation: A、B and are all non-negative numbers.
Input
Each line contain two integers A and B. Procss to end of file.(EOF)
Output
For each case, Please output the value of A multiply B
Sample Input 1
3 2
1 5
Sample Output 1
6
5
老方法,字符串输入,倒序转换为数组。
准备三个数组A,B,C
A,B来储存乘数,C来储存结果
进位时有技巧C[i+j]=C[i+j]+A[i]*B[j]
代码:
#include <stdio.h>
#include<string.h>
int main()
{
char A[1000],B[1000];
while(scanf("%s%s",&A,&B)!=EOF){
int a[1000],b[1000],c[2000];
for(int i=0;i<1000;i++){
a[i]=0,b[i]=0;
}
for(int i=0;i<2000;i++){
c[i]=0;
}
for(int i=strlen(A)-1,j=0;i>=0;i--,j++){
a[j]=A[i]-'0';
}
for(int i=strlen(B)-1,j=0;i>=0;i--,j++){
b[j]=B[i]-'0';
}
for(int i=0;i<=strlen(B)-1;i++){
for(int j=0;j<=strlen(A)-1;j++){
c[i+j]+=b[i]*a[j];
}
}
for(int i=0;i<=strlen(A)+strlen(B)-2;i++){
if(c[i]>9){
c[i+1]=c[i+1]+c[i]/10;
c[i]=c[i]%10;
}
}
int num=-1;
for(int i=strlen(A)+strlen(B)-1;i>=0;i--){
if(c[i]!=0){
num=i;
break;
}
}
if(num>=0){
for(int i=num;i>=0;i--){
printf("%d",c[i]);
}
}
else{
printf("0");
}
printf("\n");
}
return 0;
}