標籤: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
12122222222222222222222222222
Sample Output
144444444444444444444444444
原始碼:
#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;}