難度:2
1000位的書已經超過了證書的範圍了,就連 unsigned long long都只能用到64位,所以唯一的辦法就是用字符串模擬了,這就是大數加法的字符串方法(當然還有一種方法叫做離散傅里葉變換DFT,用快速傅里葉變換(FFT)優化)
這裏用的代碼是最暴力的大數乘法:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1100;
char a[maxn] , b[maxn];
int T , cas = 1;
int main() {
scanf("%d" , &T);
while(T--) {
printf("Case %d:\n" , cas++);
scanf("%s%s" , a , b);
printf("%s + %s = " , a, b);
int la = strlen(a) , lb = strlen(b);
int len = max(la , lb);
for(int i=0;i<la/2;i++) swap(a[i] , a[la-1-i]);
for(int i=0;i<lb/2;i++) swap(b[i] , b[lb-1-i]);
for(int i=0;i<la;i++) a[i] -= '0';
for(int i=0;i<lb;i++) b[i] -= '0';
for(int i=la;i<len;i++) a[i] = 0;
for(int i=lb;i<len;i++) b[i] = 0;
int c = 0;
for(int i=0;i<len;i++) {
int tmp = (a[i] + b[i] + c);
a[i] = tmp % 10;
c = tmp / 10;
}
if(c) a[len++] = c;
int i = len-1;
while(i>0 && a[i] == 0) i--;
for(;i>=0;i--) printf("%d" ,a[i]);
puts("");
if(T) puts("");
}
return 0;
}