码迷,mamicode.com
首页 > 其他好文 > 详细

A——大整数加法(HDU1002)

时间:2017-08-04 21:26:48      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:inpu   which   大于   一个   ase   使用   ber   blog   ace   

题目:
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特别注意)
下面给出大整数加法函数:
 1 string add(string a,string b)     
 2 {
 3     string c="1";            //长的那个数进位时直接在结果前面加个‘1’。
 4     int cur=0,d=0,e=0;
 5     if (a.size()<b.size())swap(a,b);  //a为长的数,b为短的。swap(a,b)交换a,b。
 6     int la=a.size();
 7     int lb=b.size();
 8     while (lb--)          //把短的那个数计算完。
 9     {
10         la--;
11         d=(cur+a[la]-0+b[lb]-0)/10;   //判断是否有进位。
12         a[la]=(cur+a[la]-0+b[lb]-0)%10+0;   
13         cur=d;
14     }
15     if (cur==1)      //如果短的那个数最后一位数还有进位。
16     while (la--)
17     {
18         e=(a[la]-0+cur)/10;
19         a[la]=(a[la]-0+cur)%10+0;
20         cur=e;
21     }
22     if (cur==1)     //如果长的那个数最后一位还有进位。
23        a=c+a;
24     return a;
25 }

 

A——大整数加法(HDU1002)

标签:inpu   which   大于   一个   ase   使用   ber   blog   ace   

原文地址:http://www.cnblogs.com/shendeng23/p/7286933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!