A + B Problem II

   之前总是在查阅别人的文档,看着其他人的博客,自己心里总有一份冲动,想记录一下自己学习的经历。学习算法有一段时间了,于是想从算法开始自己的博客生涯O(∩_∩)O~~

   今天在网上看了一道大数相加(高精度)的题目,题目很简单,但是体现了算法编程的细心之处。

   题目:A + B Problem II

   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

   /*注意哦这里是两个test之间会有一个空行*/

   Case 2:

   112233445566778899 + 998877665544332211 = 1111111111111111110

   /*在最后一个test输出之后是不需要空行的*/

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     int n;
 9     cin>>n;
10     int t = 0;
11     while(n--)
12     {
13         t++;
14         char a[1005];
15         char b[1005];
16         char c[1005] = {'0'}; //c数组用来存放两数相加之和,需要初始化一下
17         cin>>a;    //cin会忽略回车、空格、tab键
18         cin>>b;
19         int k,sum;
20         k = strlen(a)>strlen(b)?strlen(a):strlen(b); //k 取两个长整数中较长的一个
21         a[k+1]=''; // 对长整数之后的一位赋值'' 结束标志
22         sum = 0; //累加器
23         for(int i = strlen(a)-1,j=strlen(b)-1;j>=0||i>=0;i--,j--,k--)
24         {
25             if(i>=0) sum+=a[i]-'0';
26             if(j>=0) sum+=b[j]-'0';
27             c[k] = sum%10 + '0'; 
28             sum /= 10;
29         }
30         if(sum!=0)
31             c[0] = sum + '0';
32         else
33             strcpy(c,&c[1]);
34         printf("Case %d:
",t);
35         printf("%s + %s = %s
",a,b,c);
36         if(n!=0)  //最后一个test 不需要输出空行
37             printf("
");
38     }
39     return 0;
40 }
原文地址:https://www.cnblogs.com/mxk-star/p/6115814.html