POJ2389Bull Math

转载请注明出处:優YoU   http://user.qzone.qq.com/289065406/blog/1305285069

大数相乘,水题一道,直接模拟笔算竖式得了,没技巧没算法,秒杀

 

 1 //Memory Time
2 //216K 16MS
3
4 #include<iostream>
5 #include<string>
6 using namespace std;
7
8 const int size=1000; //大数位数
9
10 void mult(char* A,char* B,char* ans)
11 {
12 int a[size+1]={0};
13 int b[size+1]={0};
14 int pa=0,pb=0;
15 int c[2*size+1]={0};
16
17 int lena=strlen(A);
18 int lenb=strlen(B);
19
20 for(int i=lena-1;i>=0;i--)
21 a[pa++]=A[i]-'0';
22 for(int j=lenb-1;j>=0;j--)
23 b[pb++]=B[j]-'0';
24
25 for(pb=0;pb<lenb;pb++)
26 {
27 int w=0; //低位到高位的进位
28 for(pa=0;pa<=lena;pa++)
29 {
30 int temp=a[pa]*b[pb]+w;
31 w=temp/10;
32 temp=(c[pa+pb]+=temp%10);
33 c[pa+pb]=temp%10;
34 w+=temp/10;
35 }
36 }
37 bool flag=false;
38 bool sign=false; //标记ans是否为全0
39 for(pa=0,pb=lena+lenb-1;pb>=0;pb--)
40 {
41 if(!flag && c[pb]==0) //删除ans开头的0
42 continue;
43 else
44 flag=true;
45
46 sign=true;
47 ans[pa++]=c[pb]+'0';
48 }
49 if(sign)
50 ans[pa]='\0';
51 else
52 {
53 ans[0]='0';
54 ans[1]='\0';
55 }
56
57 return;
58 }
59
60 int main(void)
61 {
62 char a[size+1];
63 char b[size+1];
64 char ans[2*size+1];
65 while(cin>>a>>b)
66 {
67 mult(a,b,ans);
68 cout<<ans<<endl;
69 }
70 return 0;
71 }
原文地址:https://www.cnblogs.com/lyy289065406/p/2121407.html