Product UVA 10106

來源:互聯網
上載者:User

標籤: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;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.