Bull Math(大数相乘)

Problem Description
Bulls are so much better at math than the cows. They can multiply huge integers together and get perfectly precise answers … or so they say. Farmer John wonders if their answers are correct. Help him check the bulls’ answers. Read in two positive integers (no more than 40 digits each) and compute their product. Output it as a normal number (with no extra leading zeros).

FJ asks that you do this yourself; don’t use a special library function for the multiplication.

Input

  • Lines 1…2: Each line contains a single decimal number.

Output

  • Line 1: The exact product of the two input lines

Sample Input
11111111111111
1111111111

Sample Output
12345679011110987654321

题意:给出两个很大的数,输出两个数相乘的结果,没有额外前导零。
思路:前面输入数据处理和大数加法一样,不过在相乘时不同,可以按平时笔算两数相乘时,来处理。
例如:123 x 12345
          12345
     x       123
-----------------
          37035
        24690
      12345
-----------------
      1518435
找一找运算规则就会发现,两个数相乘,等于下面的数(123)从个位(3)开始,乘以上面的数(12345)得到一个值(37035),然后再是十位(2)乘上面的数(12345)得到24690,依次类推,要注意后面每次相乘需进一位,然后按位相加,就得到了结果。在运算中,可以在算的过程中直接相加,不会影响最后的结果,即算到24690时,就进一位然后按位相加37035的每一位,再继续。具体实现参考代码:

/*注意:定义存储结果的数组时必须考虑到是存储两个大数相乘的结果,范围需要定义为两个大数的范围相加,
例如两个10000相乘等于100000000!!!除去前导零时也要注意数组的位置。
*/
#include<stdio.h>
#include<string.h>
int main()
{
    int i,j,k;
    char str1[45],str2[45];
    int a[45],b[45],c[100];
    memset(a,0,sizeof(a));
    memset(b,0,sizeof(b));
    memset(c,0,sizeof(c));
    scanf("%s%s",str1,str2);//用字符串接收数据
    for(i = 0,j = strlen(str1)-1; str1[i]!='\0'; i++)//转为整数型并倒置,便于计算时进位
        a[j--] = str1[i]-'0';
    for(i = 0,j = strlen(str2)-1; str2[i]!='\0'; i++)
        b[j--] = str2[i]-'0';
    for(i = 0; i<strlen(str2); i++)//乘法运算等于a 的各个数位上的数乘以b 的各个数位上的数的和
    {
        for(j = 0,k = i; j<strlen(str1); j++,k++)//计算和时,b 第二个数乘以a 各个位时,k往左移一位,即k等于i的位(写一个两数相乘的运算步骤来理解)
        {
            c[k] += a[j]*b[i];
            c[k+1] += c[k]/10;
            c[k] = c[k]%10;
        }
    }
    for(i = 99; i>=0; i--)
    {
        if(c[i]!=0)
            break;
    }
    for(j = i; j>=0; j--)
    {
        printf("%d",c[j]);
    }
    printf("\n");
    return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值