Product(uva10106)
2014-09-08 11:36
309 查看
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; }
相关文章推荐
- UVA 10106 Product(大数相乘)
- uva 10106 Product(高精度乘法)
- UVa 10106 Product
- uva-10106 - Product
- UVa 10106 - Product
- UVA 10106-Product(大数乘法)
- (高精度运算4.7.21)UVA 10106 Product(大数乘法)
- (高精度运算4.7.21)UVA 10106 Product(大数乘法)
- UVA-10106 Product
- UVA 10106-Product
- UVA 10106 - Product (大数相乘问题)
- Uva 10106 Product(use java)
- UVA - 10106 Product
- UVA 10106 - Product
- Uva 10106 - Product
- UVa 10106 - Product
- UVa 10106 - Product
- UVA - 10106 - Product
- UVA - 10106 Product
- UVA 10106 - Product(大数乘法)