A + B Problem II(大数加法)
题目链接:A + B Problem II
问题描述
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
题目大意
给定数字a、b,计算a+b的和。例如,给定a=112233445566778899,b=998877665544332211,则和为1111111111111111110。
解题思路
由于数据过大,无法使用long long存储数据,因此使用char类型数组来储存数据,逐位进行计算
代码
#include <stdio.h>
#include <string.h>
#include <iostream>
char s1[1000], s2[1000];
int a[1000], b[1000], c[1000];
using namespace std;
int main() {
int T, count = 1;
cin >> T;
while (T--) {
// 初始化
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
memset(c, 0, sizeof(c));
long i = 0, j = 0;
// 读取a,b
scanf("%s %s", s1, s2);
cout << "Case " << count << ":" << endl;
cout << s1 << " + " << s2 << " = ";
long a_len = strlen(s1), b_len = strlen(s2);
if (a_len > b_len) {
char temp[1000];
strcpy(temp, s1);
strcpy(s1, s2);
strcpy(s2, temp);
a_len = strlen(s1);
b_len = strlen(s2);
}
//将a,b转为数字
for (i = a_len-1, j = 0; i >= 0; i--) {
a[i] = s1[i] - '0';
c[j++] = a[i];
}
for (i = b_len-1, j = 0; i >= 0; i--) {
b[i] = s2[i] -'0';
c[j++] += b[i];
}
long max_len = (a_len > b_len) ? a_len : b_len;
int temp = 0;
for (i = 0; i < max_len; i++) {
c[i] += temp;
temp = c[i] / 10;
c[i] = c[i] % 10;
if (i == max_len-1 && temp != 0) {
c[j++] = temp;
}
}
for (i = j-1; i >= 0; i--)
cout << c[i];
cout << endl;
if (T) {
cout << endl;
}
count++;
}
return 0;
}
个人学习经验,欢迎各位指导