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

大数的加法运算,杭电oj-1002

时间:2015-03-15 13:43:31      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

 
【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
【AC代码】
 1 #include<stdio.h>
 2 #include<string.h>
 3 #define max(a, b) a > b ? a:b
 4 
 5 char a[1024];
 6 char b[1024];
 7 char c[1024];
 8 int i;
 9 
10 void reverse(char *a)
11 {
12     int aa = strlen(a);
13     char t;
14     for(i=0; i<aa/2; i++)
15     {
16         t = a[i];
17         a[i] = a[aa-1-i];
18         a[aa-1-i] = t;
19     }
20 }
21 void add(char *a, char *b, char *c)
22 {
23         int cc = 0, aa = strlen(a), bb = strlen(b);
24         int len = max(aa, bb);
25            for(i=0; i<aa; i++)
26            {
27             a[i] = a[i]-0;
28         }
29            for(i=0; i<bb; i++)
30         {
31               b[i] = b[i]-0;
32         }
33         for(i=0; i<len; i++)
34         {
35             c[i] = (a[i]+b[i]+cc) % 10 + 0;
36             cc = (a[i]+b[i]+cc) / 10;
37         }
38            if(cc) c[i++] = cc + 0;
39           c[i] = \0;
40 }
41 void print(char *c)
42 {
43     for(i = strlen(c)-1; i>=0; i--)
44         printf("%c", c[i]);        
45         printf("\n");
46 }
47 main()
48 {
49     int n, j;
50     scanf("%d", &n);
51     for(j=1; j<=n; j++)
52     {
53         memset(a, 0, sizeof(a));
54         memset(b, 0, sizeof(b));
55         memset(c, 0, sizeof(c));
56         scanf("%s %s", a, b);
57         printf("Case %d:\n", j);
58         printf("%s + %s = ", a, b);
59         reverse(a), reverse(b);
60         add(a, b, c);
61         print(c);
62           if(j != n) printf("\n");
63     }
64     
65 }

 

 

大数的加法运算,杭电oj-1002

标签:

原文地址:http://www.cnblogs.com/forerve/p/4339092.html

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