码迷,mamicode.com
首页 > 其他好文 > 详细

Product UVA 10106

时间:2014-07-29 18:03:42      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:acm   算法   uva   c   源代码   

题目

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


源代码:

#include <stdio.h>
#include <string.h>
#define MAXL 250+5
#define MAXO 500+5//答案的最大长度

char x[MAXL];
char y[MAXL];
char ans[MAXO];

int main(){
 int i,j,left,k,pos,product,carry;
 int x_len,y_len;

//freopen("data","r",stdin);
while(scanf("%s%s",x,y)==2){
 ans[MAXO-1]='\0';
 k=left=MAXO-1;
 x_len=strlen(x);
 y_len=strlen(y);
 if(x_len==1&&x[0]=='0'||y_len==1&&y[0]=='0'){//若有一个乘数为0,则直接输出0,果然被这个地方坑了好久!
  printf("0\n");
  continue;
 }
 for(i=0;i<MAXO-1;i++)
 ans[i]='0';

 for(i=y_len-1;i>=0;i--){
  k--;
  pos=k;
  carry=0;
  for(j=x_len-1;j>=0;j--){
   product=(y[i]-'0')*(x[j]-'0')+ans[pos]-'0'+carry;
   ans[pos]=product%10+'0';//一个位上的数=(原来该位上的数+进位的数+乘积)取余所得
   pos--;
   carry=product/10;//一个位的进位其实包括之前那位求和的进位以及乘积的进位
  }

   while(carry){//还要对乘法结束后的进位进行处理
   carry+=ans[pos]-'0';
   ans[pos]=carry%10+'0';
   pos--;
   carry/=10;
   }

   left=left<=pos+1?left:pos+1;//left表示结果能达到的最左边的位置,输出答案时,以该位作为首地址即可
  }

  printf("%s\n",ans+left);
}

return 0;
}





Product UVA 10106,布布扣,bubuko.com

Product UVA 10106

标签:acm   算法   uva   c   源代码   

原文地址:http://blog.csdn.net/u011915301/article/details/38270825

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!