hduoj 1002 A + B Problem II

时间:2023-03-09 12:53:28
hduoj 1002 A + B Problem II

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002

题目描述如下:


A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)

Memory Limit: 65536/32768 K (Java/Others)

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

题目大意: 大数相加

题目思路: 从最低位开始一位一位的加。注意进位,注意清除前缀的0

C++ 代码如下:

#include <cstring>
#include <iostream> using namespace std; int main()
{
int n;
char a[1001],b[1001];
short c[1001];
cin >> n;
for (int i=0; i<n; i++)
{
int alen,blen,clen,maxlen;
cin >> a >> b;
alen = strlen(a);
blen = strlen(b);
clen = 0;
maxlen = alen/blen ? alen : blen;
int ai,bi,s=0;
for (int j=0; j<maxlen; j++)
{
ai = alen-j-1;
bi = blen-j-1;
if (ai>=0 && bi>=0)
s = a[ai]+b[bi]-2*'0'+s/10;
else if (ai>=0)
s = a[ai]-'0'+s/10;
else if (bi>=0)
s = b[bi]-'0'+s/10;
c[clen++] = s%10;
}
if (s/10)
c[clen++] = s/10;
for (int k=clen-1; k>=0; k--)
if (c[k])
break;
else
clen--;
cout << "Case " << i+1 << ":" << endl;
cout << a <<" + " << b << " = ";
for (int k=clen-1; k>=0; k--)
cout << c[k];
cout << endl;
if (n-i-1)
cout << endl;
}
return 0;
}