C语言版:
#include<stdio.h>
#include<string.h>
int main() {
int i, t, T, aLen, bLen, add, sum;
char a[1002], b[1002], c[1002], temp;
scanf("%d", &T);
for (t = 1; t <= T; t++) {
scanf("%s %s", a, b);
// 获取数字长度
aLen = strlen(a);
bLen = strlen(b);
// 将数字反转,使其从个位开始对齐
for (i = 0; i<aLen / 2; i++) {
temp = a[i];
a[i] = a[aLen - i - 1];
a[aLen - i - 1] = temp;
}
for (i = 0; i<bLen / 2; i++) {
temp = b[i];
b[i] = b[bLen - i - 1];
b[bLen - i - 1] = temp;
}
add = 0;
// 开始模拟加法
for (i = 0; i<aLen || i<bLen; i++) {
if (i<aLen && i<bLen)
sum = a[i] - '0' + b[i] - '0' + add;
else if (i < aLen)
sum = a[i] - '0' + add;
else if (i < bLen)
sum = b[i] - '0' + add;
add = 0;
if (sum > 9) {
add = 1;
sum -= 10;
}
c[i] = sum + '0';
}
// 若加完后还有进位,则补上
if (add) c[i++] = add + '0';
// 逆序输出相加的和
printf("Case %d:\n", t);
for (i--; i >= 0; i--)
printf("%c", c[i]);
puts("\n");
}
return 0;
}
C++版:
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main() {
int i, T, aLen, bLen, add, sum;
string a, b, c;
cin >> T;
for (int t = 1; t <= T; t++) {
cin >> a >> b;
// 获取字符串长度
aLen = a.length();
bLen = b.length();
// 反转a和b,使其从个位开始对齐
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
c = ""; // c=a+b
add = 0; // 进位
// 开始模拟加法
for (i = 0; i<aLen || i<bLen; i++) {
if (i<aLen && i<bLen)
sum = a[i] - '0' + b[i] - '0' + add;
else if (i < aLen)
sum = a[i] - '0' + add;
else if (i < bLen)
sum = b[i] - '0' + add;
add = 0;
if (sum > 9) {
add = 1;
sum -= 10;
}
c += sum + '0';
}
// 若加完后还有进位,则补上
if (add) c += add + '0';
// 逆序并输出
reverse(c.begin(), c.end());
cout << "Case " << t << ":" << endl;
cout << c << endl << endl;
}
return 0;
}
Java版:
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int T;
BigInteger a, b;
Scanner in = new Scanner(System.in);
T = in.nextInt();
for (int t = 1; t <= T; t++) {
a = new BigInteger(in.next());
b = new BigInteger(in.next());
System.out.println("Case " + t + ":");
System.out.println(a.add(b) + "\n");
}
in.close();
}
}