【POJ2389】Bull Math(大数乘法)

Bull Math

Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu
Submit

Status

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).

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"
#include "algorithm"

using namespace std;

const int maxn = 1e2+5;

string str1,str2;

string sum(string s1,string s2)  //大数加法  
{  
    if(s1.length()<s2.length())  
    {  
        string temp=s1;  
        s1=s2;  
        s2=temp;  
    }  
    int i,j;  
    for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--)  
    {  
        s1[i]=char(s1[i]+(j>=0?s2[j]-'0':0));    
        if(s1[i]-'0'>=10)  
        {  
            s1[i]=char((s1[i]-'0')%10+'0');  
            if(i) s1[i-1]++;  
            else s1='1'+s1;  
        }  
    }  
    return s1;  
} 

string Mult(string s,int x)  //大数乘以整形数  
{  
    reverse(s.begin(),s.end());  
    int cmp=0;  
    for(int i=0;i<s.size();i++)  
    {  
        cmp=(s[i]-'0')*x+cmp;  
        s[i]=(cmp%10+'0');  
        cmp/=10;  
    }  
    while(cmp)  
    {  
        s+=(cmp%10+'0');  
        cmp/=10;  
    }  
    reverse(s.begin(),s.end());  
    return s;  
}  

string Multfa(string x,string y)  //大数乘法  
{  
    string ans;  
    for(int i=y.size()-1,j=0;i>=0;i--,j++)  
    {  
        string tmp=Mult(x,y[i]-'0');  
        for(int k=0;k<j;k++)  
            tmp+='0';  
        ans=sum(ans,tmp);  
    }  
    return ans;  
}  

int main(){
        cin>>str1;
        cin>>str2;
        string gao = Multfa(str1,str2);
        cout<<gao<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值