1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Add a, b, and carry. Return the least significant digit
// and update carry.
int
sum(int a, int b, int &carry)
{
int result = a+b+carry;
if (result >= 10) {
result -= 10;
carry = 1;
} else {
carry = 0;
}
return result;
}
string
add(string a, string b)
{
int s {0}, carry {0};
if (b.length() > a.length() ||
(b.length() == a.length() && b[0] - '0' > a[0] - '0')) {
swap(a, b);
}
string c = "";
int i = a.length() - 1, j = b.length() - 1;
while (i >= 0) {
if (j < 0) {
s = sum(a[i] - '0', 0, carry);
// c += sum(a[i] - '0', m, 1);
i--;
} else {
s = sum(a[i] - '0', b[j] - '0', carry);
i--;
j--;
}
c += s+'0';
}
if (carry)
c += '1';
for (int i = 0; i <= (c.length() - 1) / 2; i++)
swap(c[i], c[c.length() - 1 - i]);
return c;
}
int
main()
{
ifstream f("input.txt");
ofstream g("sum.txt");
string s, s2;
f >> s >> s2;
g << add(s, s2);
f.close();
g.close();
return 0;
}
|