12.4 大数乘法

Description

Now Give you two integers AA and BB , please caculate the value of AA multiply BB.Attation: AA、BB and are all non-negative numbers.

Input

Each line contain two integers AA and BB. Procss to end of file.(EOFEOF)

Output

#include <stdio.h>
#include <string.h>
int main()
{
    char a[1000],b[1000];
            int l[1000],l1[1000],l2[1000];
        int c,d,i,j,e,k,p,q,aa,bb,ii,jj;
    while(scanf("%s %s",&a,&b)!=EOF){
        c=strlen(a);
        d=strlen(b);
        // 将字符串存入数字中
        for(i=0;i<c;i++){
            l[i]=a[c-1-i]-'0';
        }
        for(j=0;j<d;j++){
           l1[j]=b[d-1-j]-'0';
        }
        //  如果有一个数为0,则输出0,不然答案会有好多0
        if(l1[0]==0&&d==1){
            printf("%d\n",0);
            continue;
        }
            else if(l[0]==0&&c==1){
            printf("%d\n",0);
            continue;
        }
        else{
        aa=d;
        bb=0;jj=0;
        //   遵循乘法竖式法则  先将每个位的数存到相印位置
        while(aa>0){
                for(ii=0;ii<c;ii++){
                    l2[jj]=l2[jj]+l[ii]*l1[bb];
                    jj++;
                }
                aa=aa-1;
                bb++;		//bb是第二个数的位数的索引值,
                jj=bb;             // jj是每次相乘得到的数的第一个位置
        }
        // 判断进位
        for(k=0;k<jj+c-2;k++){            /*结果的最高为为最后一次for循环后jj的值,推出来就是jj+c-2.,(因为最后b加了1所以减1,因为c是
        长度,索引值还需要-1)   */
                if(l2[k]>9){
                    l2[k+1] += l2[k]/10;
                    l2[k]=l2[k]%10;
                }
        }
        for(p=jj+c-2;p>=0;p--){
            printf("%d",l2[p]);
            l2[p]=0;l[p]=0;l1[p]=0;
        }
        printf("\n");
    }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43763889/article/details/84797620