您的位置:首页 > 其它

B - A + B Problem II HDU - 1002 (大数相加问题)

2017-11-12 21:46 405 查看
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

s思路及要点

这是一道很典型的大数运算问题,我们可以利用字符串来模拟竖式运算的方法解决。注意的要点有:1、字符型数组要转化为整形数组,需要在每一位上减去‘0’(即字符型的0)。2、为了方便运算,我们需要将加数与被加数的最低位对齐,所以在将字符数组转化为整形数组时,可以将数组逆序排列,保证最低位对齐。3、注意进位。4、由于运算时数组已被逆置,所以在输出时,需要逆序输出,才能保证结果正确。5、注意输出格式,是一次换行还是两次换行。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
char a[1005], b[1005];
int main()
{
int t;
while(scanf("%d", &t) != EOF){
int kase = 0;
while(t--){
scanf("%s%s", a, b);
int numa[1005] = {0}, numb[1005] = {0}, numc[1005] = {0};
int len_a = strlen(a), len_b = strlen(b);
int ma = max(len_a, len_b);
for(int i = len_a - 1; i >= 0; i--)
numa[len_a - 1 - i] = a[i] - '0';
for(int j = len_b - 1; j >= 0; j--)
numb[len_b - 1 - j] = b[j] - '0';
for(int i = 0; i < ma; i++)
numc[i] = numa[i] + numb[i];
for(int i = 0; i < ma; i++){
if(numc[i] >= 10){
if(i == ma - 1)ma++;
numc[i] -= 10;
numc[i+1]++;
}
}
if(kase)printf("\n");
printf("Case %d:\n%s + %s = ", ++kase, a, b);
for(int i = ma - 1; i >= 0; i--)
printf("%d", numc[i]);
printf("\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: