浙大1027 大数的乘法

                                   大数的乘法

Description:
给出一些整数对,一个为可能接近100位的大数,另一个为1位数,求这些数对的乘积。

Sample Input:
1 1
123 0
12345678910 8
123456789101234567891012345678910 7
Sample Output:
1
0
98765431280
864197523708641975237086419752370

解答:

#include <iostream>
#include <string>
using namespace std;//所有的函数放在这句下面
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;  //字符转化为数字(即减去字符0)
  c=0;
  while(tmp>9)//要用while,比如说tmp=27,就有两次进位
  {
   tmp-=10;
   c++;   
   
  } 
   a[i]=tmp+'0';    //数字再转化成字符存到string数组中去
 }    
  if(c>0) a.insert(a.begin(),c+'0');  
    //如果第一位也出现进位,就把数组自动扩充一位用来存进位
    // insert这个操作时是将字符插入到迭代器的前一个位置
//也就是说插入的那个字符变成第一位,其余的右移
}

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;
}

posted on 2010-03-21 17:57  蓝牙  阅读(241)  评论(0编辑  收藏  举报