A——大整数加法(HDU1002)

时间:2023-03-08 22:07:39
A——大整数加法(HDU1002)
题目:
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B. 

InputThe 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. 
OutputFor 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
解题思路:
既然是大整数,肯定就不能用实型来储存变量,在这里使用字符串string类型来进行模拟运算。(即:从个位数加起,大于10就进1,以此类推。)
有两个进位的地方需要注意!一个是当短的那个数加完时,另一个是长的那个数加完时(比如:1+9999和543+457特别注意)
下面给出大整数加法函数:
 string add(string a,string b)
{
string c=""; //长的那个数进位时直接在结果前面加个‘1’。
int cur=,d=,e=;
if (a.size()<b.size())swap(a,b); //a为长的数,b为短的。swap(a,b)交换a,b。
int la=a.size();
int lb=b.size();
while (lb--) //把短的那个数计算完。
{
la--;
d=(cur+a[la]-''+b[lb]-'')/; //判断是否有进位。
a[la]=(cur+a[la]-''+b[lb]-'')%+'';
cur=d;
}
if (cur==) //如果短的那个数最后一位数还有进位。
while (la--)
{
e=(a[la]-''+cur)/;
a[la]=(a[la]-''+cur)%+'';
cur=e;
}
if (cur==) //如果长的那个数最后一位还有进位。
a=c+a;
return a;
}