题目比较拗口的大数相加,两个数居然分开一个数字一个数字读入,注意要用scanf()读入,cin因为重载,没有指定格式,输入比较耗时。同时输出也要先转换为字符串形式,不然循环输出整数数组会超时。 #include <iostream> #include <cstdio> #include <cstring> using namespace std; int n; // 输入长度 int main() { //freopen("temp.txt", "r", stdin); cin >> n; int *a = new int[n]; int *b = new int[n]; int *ans = new int[n]; char *ansc = new char[n+1]; for (int i = n-1; i >= 0; --i) scanf("%d %d", &a[i], &b[i]); memset(ans, 0, sizeof(ans) * n); //当ans为int ans[n]时,用sizeof是不同的 int carry = 0; for (int i = 0; i < n; ++i) { //这题居然结果与输入结果长度一致 ans[i] += a[i] + b[i] + carry; carry = ans[i] / 10; ans[i] = ans[i] % 10; } for (int i = 0; i < n; ++i) // 这里不能直接循环输出ans,会超时 ansc[i] = ans[n-1-i] + '0'; ansc[n] = '\0'; cout << ansc << endl; return 0; }