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
分析:这道题就是很多很多很多很多细节要注意,这串代码还有很多可以改进的地方,接下来我去优化一下。做题的过程中想到很多操作,但是由于自己水平未够,最后只能放弃。
大概的思路就是弄三个char型数组,a储存输入数1,b储存输入数2.
然后比较哪个长,然后让一个变量如i记住长的数组的有效长度(应该是这样叫吧)
然后第三个数组c从i开始记a最后一个有效字符与b最后一个有效字符之和,如果和大于9就-10,然后通过一个变量记录然后在下一次相加时结果加1记录。短的加完以后长的没加的copy到c那里,期间要注意开始copy时当前正在copy的数是否要+1。
ac代码
#include <iostream>
#include<string>
using namespace std;
void what(char a[], char b[], char c[])
{
int i1 = strlen(a);
int i3 = 0;
for (int i = strlen(b);i != 0;i--)
{
int _a, _b, _c;
_a = a[i1 - 1] - 48;
_b = b[i - 1] - 48;
if (i == 1)
{
if (strlen(a) == strlen(b))
if (_a + _b > 9 || _a + _b > 8 && i3 == 1)
{
for (int i4 = strlen(a);i4 != 0;i4--)
c[i4] = c[i4 - 1];
c[strlen(a) + 1] = 0;
}
}
if (_a + _b > 9 || _a + _b > 8 && i3 == 1)
{
if (i == 1)
{
c[i1-1] = 48 + _a + _b - 10;
if (i3 == 1)
{
c[i1-1] += 1;
if (c[i1-1] > '9')
c[i1-1] -= 10;
}
i3 = 1;
}
else
{
c[i1 - 1] = 48 + _a + _b - 10;
if (i3 == 1)
{
c[i1 - 1] += 1;
if (c[i1 - 1] > '9')
c[i1 - 1] -= 10;
}
i3 = 1;
}
}
else
{
c[i1 - 1] = 48 + _a + _b;
if (i3 == 1)
{
c[i1 - 1] += 1;
if (c[i1 - 1] > '9')
c[i1 - 1] -= 10;
}
i3 = 0;
}
i1--;
}
if (strlen(a) != strlen(b))
{
for (;i1 != 0;i1--)
{
c[i1 - 1] = a[i1 - 1];
if (i3 == 1)
{
c[i1 - 1] += 1;
if (c[i1 - 1] > '9')
{
c[i1 - 1] -= 10, i3 = 1;
if (i1 - 1 == 0)
{
for (int i4 = strlen(a);i4 != 0;i4--)
c[i4] = c[i4 - 1];
c[strlen(a) + 1] = 0;
c[0] = '1';
}
}
else i3 = 0;
}
}
}
}
int main()
{
int T;
cin >> T;
for (int i2 = 1;i2 <= T;i2++)
{
cout << "Case " << i2 << ":" << endl;
char a[1010] = { 0 }, b[1010] = { 0 }, c[1010] = { 0 };
cin >> a >> b;
if (strlen(a) >= strlen(b))
{
what(a, b, c);
}
else
{
what(b, a, c);
}
cout << a << " + " << b << " = " << c << endl;
if (i2 != T)
cout << endl;
}
}