首页 > 代码库 > [HDU1002] A + B Problem II

[HDU1002] 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

 

分析

说这是个very simple problem,其实是在坑你的~用计算A+B的普通方法是不行的,必须要高精度算法。

 

高精度求和算法

 

高精度算法就是模拟手算。举个例子,计算12345+67890,写成竖式的形式:

 

   1 2 3 4 5

+ 6 7 8 9 0

---------------

    ? ? ? ? ?

先计算个位,5+0=5,结果的个位是5:

 

   1 2 3 4 5

+ 6 7 8 9 0

---------------

    ? ? ? ? 5

 

接着计算十位,4+9=13,结果的十位是3,因为13>=10,产生了1的进位:

 

   1 2 3 4 5

+ 6 7 8 9 0

---------------

    ? ? ? 3 5

 

然后计算百位,3+8=11,再加1的进位,12,结果的百位是2,因为12>=10,产生了1的进位:

 

   1 2 3 4 5

+ 6 7 8 9 0

---------------

    ? ? 2 3 5

 

后面计算千位,2+7=9,加1的进位,10,结果的千位是0,因为10>=10,产生1的进位:

 

   1 2 3 4 5

+ 6 7 8 9 0

---------------

    ? 0 2 3 5

 

最后计算万位,1+6=7,加1的进位,8,因为8<10,所以这次没有进位了:

 

   1 2 3 4 5

+ 6 7 8 9 0

---------------

    8 0 2 3 5

 

因此结果是80235。

 

同理,在程序里,使用两个int数组存储输入的两个数,每个数组元素都代表了一位(因为一位是0~9,所以还可以更小些,char就够了)。这里因为说每个数的长度不会超过一千,因此声明两个数组a和b:

 

int a[1000], b[1000];

 

两个长度不超过1000的数,最大都是1000个9,和为199...998(999个9),是1001位数,因此用于保存结果的数组c如下:

 

int c[1001];

 

注意:文章未完成,请勿转载。

NOTICE: PASSAGE IS NOT FINISHED, DO NOT REPRODUCE.

AVERTISSEMENT: ARTICLE N‘EST PAS COMPLéTé. NE REPRODUISEZ PAS.

[HDU1002] A + B Problem II