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

详细题目点击:?pid=1002

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

21 2112233445566778899 998877665544332211

Sample Output

Case 1:1 + 2 = 3Case 2:112233445566778899 + 998877665544332211 = 1111111111111111110

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

#include <stdio.h>#include <stdlib.h>#include <string.h>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;}elsecarry = 0;i++;lena–;}while(lenb >= 0){c[i] = c[i] + b[lenb] + carry;if(c[i] > '9'){c[i] -= 10;carry = 1;}elsecarry = 0;i++;lenb–;}lenc = strlen(c);printf("Case %d:\n", j);printf("%s + %s = ", a, b);for(i = lenc-1; i >= 0; i–) //c数组中c[0]存放的是大数的最低位,,c[lenc-1]存放的是大数的最高位printf("%c", c[i]);printf("\n");if(j != n)printf("\n");}return 0;}

参考资料:

1、(网上资料)hdu 1002 A + B Problem II 大整数相加

勇于接受自己的不完美,认清自己不足的地方,

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

相关文章:

你感兴趣的文章:

标签云: