A + B Problem II |
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
Total Submission(s): 3947 Accepted Submission(s): 1386 |
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
|
Author
Ignatius.L
|
这道题看似简单,实则是个大数相加问题,显然其位数已超过基本数据类型所能表示的最大大小。针对此题,基本思路如下:
1、将输入作为字符串保存,逐位进行单个字符的相加。
注意事项:
1、由于字符串的第一个字符表示数值的最高位,最后一个字符表示数值的最低位,因此在进行逐位相加前,应将两个加数先逆序,在相加。
2、相加计算时应该不要忽略进位以及两个加数位数不等的情况,还有就是相加的是字符的ASCII码值,因注意与字符‘0’做个数值转换哦。
3、输出的格式不对也不能AC的哦。
code:
#include <iostream>
using namespace std;
char a[1001] = { 0 };
char b[1001] = { 0 };
char a1[1001] = { 0 };
char b1[1001] = { 0 };
char sum[1002] = { 0 };
int main()
{
int n;
int cnt = 0;
int length_a1;
int length_b1;
cin >> n;
cnt = n;
while (n--)
{
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
memset(a1, 0, sizeof(a1));
memset(b1, 0, sizeof(b1));
memset(sum, 0, sizeof(sum));
cin >> a1;
cin >> b1;
// 逆序
length_a1 = strlen(a1);
int index = length_a1 - 1;
for (; index >= 0; index--)
{
a[length_a1 - 1 - index] = a1[index];
}
length_b1 = strlen(b1);
index = length_b1 - 1;
for (; index >= 0; index--)
{
b[length_b1 - 1 - index] = b1[index];
}
int i = 0;
int carry = 0;
while ((a[i] != 0) && (b[i] != 0)) // 两个都不为0
{
int tmp = (a[i] - '0') + (b[i] - '0') + carry;
if (tmp >= 10)
{
tmp = tmp - 10;
carry = 1;
}
else
{
carry = 0;
}
sum[i] = 0 + tmp + 48;
i++;
}
if(length_a1 > length_b1)
{
while (a[i] != 0)
{
int tmp = 0 + (a[i] - '0') + carry;
if (tmp >= 10)
{
tmp = tmp - 10;
carry = 1;
}
else
{
carry = 0;
}
sum[i] = 0 + tmp + 48;
i++;
}
}
else
{
while (b[i] != 0)
{
int tmp = 0 + (b[i] - '0') + carry;
if (tmp >= 10)
{
tmp = tmp - 10;
carry = 1;
}
else
{
carry = 0;
}
sum[i] = 0 + tmp + 48;
i++;
}
}
if (carry == 1)
{
sum[i] = 1 + 48;
}
cout << "Case " << cnt - n << ":" << endl;
cout << a1 << " + " << b1 << " = ";
// 逆序输出
int k = strlen(sum) - 1;
for (; k >= 0; k--)
{
cout << sum[k];
}
if (n == 0)
{
cout << endl;
}
else
{
cout << endl << endl;
}
}
return 0;
}