hdu 1002 A + B Problem II
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
思路:将数字放入字符数组中,逆序相加
代码实现及讲解:
#include<stdio.h>
#include <iostream>
#include <algorithm>
#include<string.h>
#include<math.h>
using namespace std;
int main()
{
int T;
scanf("%d",&T);
int count = T;
while (T--)
{
char a[1001]; //字符数组记录数字 A ,B ,答案 ans
char b[1001];
char ans[1002];
scanf("%s",a);
scanf("%s",b);
strrev(a); //调用内置函数对字符数组进行逆序操作
strrev(b);
int len1 = strlen(a);
int len2 = strlen(b);
int i;
int one = 0;
int temp;
if (len1 > len2)
{
for (i=0;i<len2;i++)
{
temp = a[i] - '0' + b[i] - '0' + one;
one = temp / 10;
temp = temp % 10;
ans[i] = temp + '0';
}
while (i<len1) //将多余的部门直接移入ans 数组
{
temp = a[i] - '0' + one;
one = one / 10;
temp = temp % 10;
ans[i] = temp + '0';
i++;
}
if (one) //判断最后一位是否进位
{
ans[i] = one + '0';
i++;
}
ans[i] = '\0';
strrev(ans); //ans 数组逆序即为答案
}
else
{
for (i=0;i<len1;i++)
{
temp = a[i] - '0' + b[i] - '0' + one;
one = temp / 10;
temp = temp % 10;
ans[i] = temp + '0';
}
while (i<len2)
{
temp = b[i] - '0' + one;
one = one / 10;
temp = temp % 10;
ans[i] = temp + '0';
i++;
}
if (one)
{
ans[i] = one + '0';
i++;
}
ans[i] = '\0';
strrev(ans);
}
strrev(a);
strrev(b);
cout<<"Case "<<count-T<<":"<<endl<<a<<"+"<<b<<"="<<ans<<endl;
if (T != 0)
cout<<endl;
}
return 0;
}