HDU 1002 A + B Problem II(两个大数相加)

2015-07-20 17:11:36 来源: 作者: 浏览: 2

?

?

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

?

分析:对于此题做法有两种:其一,使2字符串的中的字符数字减去'0',逐个相加大于等于10的可以使本位减10,下一位自增1,后面的处理就非常简单了;其二,便是读入字符串后先让各个字符减'0',一一对应存入整形数组中;之后再相加。对于2种方法大致是相同的,都要从后面向前加,逢十进位,以及数组初始化均要初始为0,一边方便运算。

?

#include 
  
   
#include 
   
     #include 
    
      char a[1001]; //开辟两个字符数组a、b,作为两个输入的大数 char b[1001]; char c[1002]; int main(void) { int carry = 0, n, j; int lena, lenb, i, lenc; scanf(%d, &n); for(j = 1; j <= n; j++) { memset(a, 0, 1001); memset(b, 0, 1001); memset(c, 0, 1002); scanf(%s, a); scanf(%s, b); lena = strlen(a); lenb = strlen(b); for(lena--, lenb--, i = 0, carry = 0; (lena >= 0) && (lenb >= 0); lena--, lenb--, i++) { c[i] = a[lena]-'0' + b[lenb]-'0' + carry; if((int)c[i] > 9) { c[i] = c[i] - 10 + '0'; carry = 1; } else { c[i] += '0'; carry = 0; } } while(lena >= 0) { c[i] = c[i] + a[lena] + carry; //有可能加上carry后还可以向前进位 if(c[i] > '9') { c[i] -= 10; carry = 1; } else carry = 0; i++; lena--; } while(lenb >= 0) { c[i] = c[i] + b[lenb] + carry; if(c[i] > '9') { c[i] -= 10; carry = 1; } else carry = 0; i++; lenb--; } lenc = strlen(c); printf(Case %d: , j); printf(%s + %s = , a, b); for(i = lenc-1; i >= 0; i--) //c数组中c[0]存放的是大数的最低位,c[lenc-1]存放的是大数的最高位 printf(%c, c[i]); printf( ); if(j != n) printf( ); } return 0; }
    
   
  

?

-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: