Product(uva10106)

 Product 

The Problem

The problem is to multiply two integers X, Y. (0<=X,Y<10250)

The Input

The input will consist of a set of pairs of lines. Each line in pair contains one multiplyer.

The Output

For each input pair of lines the output line should consist one integer the product.

Sample Input

12
12
2
222222222222222222222222

Sample Output

144
444444444444444444444444

题意:求两个数相乘的积,即大数相乘

方法:将两个大数按照string字符串输入,其中一个string和另一个string上的每一个数相乘,所得的结果保存在string数组里,然后用大数相加求得最后结果

#include<stdio.h>
#include<algorithm>
#include<string>
#include<iostream>
using namespace std;
string add(string a,string d,int cnt)   //大数相加函数
{
    string ss,b;
    int i,temp,v=0;
    for(i=0; i<cnt; i++)
        b+="0";
    b+=d;
    if(a.size()<b.size())   //将字符串长的赋给string a,短的赋给string b
    {
        ss=a;
        a=b;
        b=ss;
    }
    for(i=0; i<b.size(); i++)   //将长度相同部分相加
    {
        temp=a[i]-'0'+b[i]-'0'+v;
        a[i]=temp%10+'0';
        v=temp/10;
    }
    for(i=b.size(); i<a.size(); i++) //将string a中多出来的部分+进位v,继续进行操作
    {
        temp=a[i]-'0'+v;
        a[i]=temp%10+'0';
        v=temp/10;
    }
    if(v==1)        //如果最后存在进位
        a=a+"1";
    return a;
}
void mul(string a,string b)
{
    int i,j,temp,k=0,h,l=0;
    string c[30000],x;      
    reverse(a.begin(),a.end());     //先将两string倒置
    reverse(b.begin(),b.end());
    for(i=0; i<a.size(); i++)       //其中一个串中的一位去乘另一个串的每一位
    {
        h=0;
        k=0;
        for(j=0; j<b.size(); j++)
        {
            temp=(a[i]-'0')*(b[j]-'0')+k;
            // c[l][h++] = char(temp % 10 + '0');
            c[l] += char(temp%10+'0');      //求得的结果保存在string数组里
            k=temp/10;
        }
        if(k!=0)
            c[l] += char(k+'0');        
        //  cout<<c[l]<<endl;
        l++;
    }
    x=c[0];
    for(i=1; i<l; i++)
    {
        x=add(x,c[i],i);        //调用大数相加函数
    }
    reverse(x.begin(),x.end());
    cout<<x<<endl;
}

int main()
{
    string a,b,x;
    int i;
    while(cin>>a>>b)
    {
        if(a=="0"||b=="0")
        {
            cout<<"0\n";
            continue;
        }
        mul(a,b);
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值