C/C++ N位数加法

昨天从老师那里得知了杭电ACM这东东,于是今天就在上面做题

感觉还真是坑,输出的格式必须完全一模一样,确实是需要很严谨

先把算法贴上来 大数相加 或许以后自己还能用得上呢….23333

这个算法感觉也还能优化一下,写得好乱,是还需要多练习啊

《C/C++ N位数加法》

[cpp]
#include <iostream>
#include <string>
using namespace std;
int main(void) {
int n;
string a, b, sum;
cin >> n;
if (n > 20 || n < 0)return 0;
for (int i = 1; i <= n; i++) { sum = ""; cin >> a >> b;
cout << "Case " << i << ":" << endl << a << " + " << b << " = ";
if (a.length() < b.length()) {
string tmp = a; a = b; b = tmp; tmp = "";
}
int len = a.length();
int remain = 0, add = 0, result = 0;
char buffer[20];
for (int i1 = 1; i1 <= len; i1++) {
string a1, b1 = "0";
a1.assign(a, a.length() – i1, 1);
if (i1 <= b.length())
b1.assign(b, b.length() – i1, 1);
add = atoi(a1.c_str()) + atoi(b1.c_str()) + result;
remain = add % 10;
result = add / 10;
int nT = remain;
_itoa_s(nT, buffer, 10);
sum = buffer + sum;
}
if (result == 1)
sum = "1" + sum;
cout << sum << endl;
if (i != n)cout << endl;
}
return 0;
}
[/cpp]

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据