浙大1027 大數(shù)的乘法
大數(shù)的乘法
Description:
給出一些整數(shù)對(duì),一個(gè)為可能接近100位的大數(shù),另一個(gè)為1位數(shù),求這些數(shù)對(duì)的乘積。
Sample Input:
1 1
123 0
12345678910 8
123456789101234567891012345678910 7
Sample Output:
1
0
98765431280
864197523708641975237086419752370
解答:
#include <iostream>
#include <string>
using namespace std;//所有的函數(shù)放在這句下面
void mul(string &a,int b)
{
int tmp,c=0,len=a.size();
for(int i=len-1;i>=0;i--)
{
tmp=(a[i]-'0')*b+c; //字符轉(zhuǎn)化為數(shù)字(即減去字符0)
c=0;
while(tmp>9)//要用while,比如說(shuō)tmp=27,就有兩次進(jìn)位
{
tmp-=10;
c++;
}
a[i]=tmp+'0'; //數(shù)字再轉(zhuǎn)化成字符存到string數(shù)組中去
}
if(c>0) a.insert(a.begin(),c+'0');
//如果第一位也出現(xiàn)進(jìn)位,就把數(shù)組自動(dòng)擴(kuò)充一位用來(lái)存進(jìn)位
// insert這個(gè)操作時(shí)是將字符插入到迭代器的前一個(gè)位置
//也就是說(shuō)插入的那個(gè)字符變成第一位,其余的右移
}
int main()
{string a;
int b;
while(cin>>a>>b)
{
if(b==0)cout<<'0'<<endl;
else if(b==1) cout<<a<<endl;
else
{
mul(a,b);
cout<<a<<endl;
}
}
system("pause");
return 0;
}
文章來(lái)源:
http://www.cnblogs.com/qnbs1/archive/2010/03/21/1691076.html