#include <bits/stdc++.h>
using namespace std;
char ca[1001];
char cb[1001];
int a[1001];
int b[1001];
int c[1001];
int main() {
int l1;
int cnt = 0;
cin.getline(ca, 1001);
cin.getline(cb, 1001);
int l = strlen(ca);
int l2 = strlen(cb);
l1 = l > l2 ? l : l2;
for (int i = 0; i < l; i++) {
a[i] = ca[l - 1 - i] - '0';
}
for (int i = 0; i < l2; i++) {
b[i] = cb[l2 - 1 - i] - '0';
}
for (int i = 0; i < l1; i++) {
c[i] = a[i] + b[i] + cnt;
if (c[i] >= 10) {
c[i] %= 10;
cnt = 1;
} else {
cnt = 0;
}
}
if ( cnt == 1) {
c[l1] = 1;
l1++;
}
for (int i = l1 - 1; i >= 0; i--) {
cout << c[i];
}
return 0;
}
共 2 条回复
改成
#include #include using namespace std; string a1, b1; int a[505], b[505], c[505]; int main(void) { cin >> a1 >> b1; int lena = a1.size(); int lenb = b1.size(); for (int i = 0; i < lena; i++) a[lena - i] = a1[i] - '0'; for (int i = 0; i < lenb; i++) b[lenb - i] = b1[i] - '0'; int lenc = 1; int x = 0; while (lenc <= lena || lenc <= lenb) { c[lenc] = a[lenc] + b[lenc] + x; x = c[lenc] / 10; c[lenc] %= 10; lenc++; } c[lenc] = x; if (c[lenc] == 0) lenc--; for (int i = lenc; i >= 1; i--) cout << c[i]; return 0; }