HDU 1002 A + B Problem II 高精度加法
Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
Sample Input
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
这道题就是A+Bproblem的坑爹版本,数据很大,不能像原本可以直接long long 过掉,所以要用到一个神奇的东西,高精度加法。。
开始单纯以为是高精度,然后WA了无数次,最后发现其实有很多地方考虑还是很欠缺的,例如前导零之类的。
一直WA的同学可以尝试一下下面的几组数据:
0001 1000
00 00
000 0000
99999 0001
1 99999
99990 00999
00999 99990
(感谢world_ding提供的数据)
代码如下(稍微写得麻烦了一点):
1 var a,b:ansistring; 2 c,d,e:array[1..1010] of integer; 3 n,m:int64; 4 x,ii:longint; 5 bo:boolean; 6 j,i:integer; 7 begin 8 readln(x); 9 for ii:=1 to x do 10 begin 11 fillchar(e,sizeof(e),0); 12 fillchar(c,sizeof(c),0); 13 fillchar(d,sizeof(d),0); 14 readln(b); 15 bo:=false; 16 n:=pos(' ',b); 17 a:=copy(b,1,n-1); 18 delete(b,1,n); 19 m:=length(a); 20 n:=length(b); 21 if ii<>1 then 22 writeln; 23 write('Case '); 24 write(ii); 25 writeln(':'); 26 write(a); 27 write(' + '); 28 write(b); 29 write(' = '); 30 if n>=m then j:=n else j:=m; 31 for i:=m downto 1 do 32 begin 33 val(a[i],c[m+1-i]); 34 end; 35 for i:= n downto 1 do 36 begin 37 val(b[i],d[n+1-i]); 38 end; 39 for i:=1 to j do 40 begin 41 e[i]:=c[i]+d[i]+e[i]; 42 43 e[i+1]:=e[i] div 10 +e[i+1]; 44 e[i]:=e[i] mod 10 ; 45 end; 46 if e[j+1]=0 then dec(j); 47 i:=j+1; 48 while (i>0)do 49 begin 50 if (e[i]<>0) then 51 begin 52 write(e[i]); 53 bo:=true; 54 dec(i); 55 break; 56 end; 57 dec(i); 58 end; 59 while (i>0)do 60 begin 61 write(e[i]); 62 dec(i); 63 end; 64 if not bo 65 then write(0); 66 writeln; 67 end; 68 end.