大数乘法 poj2389

Bull Math
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 14972 Accepted: 7695

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

题意:输入两个大数,输出它们相乘的结果。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>

#define MAX 10000

using namespace std;

typedef struct bignum   //定义大数类型
{
    bignum(){memset(arr,0,sizeof(arr));length=0;}   //初始化成员变量
    int arr[MAX*2];
    int length;
}Bignum;

char s[MAX];
char t[MAX];

Bignum atoi(char *s)   //字符串转换为大数类型
{
    Bignum res;
    int slen=strlen(s);
    for(int k=slen-1;k>=0;k--)
    {
        res.arr[k]=s[k]-'0';
    }
    res.length=slen;
    return res;
}

//大数相乘
Bignum quickmul(Bignum a,Bignum b)
{
    Bignum res;  //存放结果
    for(int i=0;i<a.length;i++)
    {
        for(int j=0;j<b.length;j++)
        {
            res.arr[i+j+1]+=a.arr[i]*b.arr[j];   //将a,b按位相乘
        }
    }
    res.length=a.length+b.length;  //记得长度要更新

    //处理进位
    int temp=0;  //temp表示进位
    for(int i=res.length-1;i>=0;i--)   //从后往前处理
    {
        int sum=res.arr[i]+temp;
        res.arr[i]=sum%10;
        temp=sum/10;
    }
    if(temp)                   //如果处理到最高位依然有进位,(左->右==>>高位->低位)
        res.arr[0]=temp;
    if(res.arr[0]==0)          //如果res.arr[0]为0,把这个0去掉
    {
        for(int i=0;i<res.length-1;i++)
            res.arr[i]=res.arr[i+1];
        res.length--;
    }


    return res;
}

//输出大数
void print(Bignum b)
{
    for(int i=0;i<b.length;i++)
        cout<<b.arr[i];
    cout<<endl;
}

int main()
{
    while(cin>>s>>t)
    {
        Bignum a=atoi(s);
        Bignum b=atoi(t);
        print(quickmul(a,b));
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/f-society/p/6705760.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值