#include <iostream> #include <string.h> using namespace std; char* add(string a, string b) { const int N = 5005; char res[N] = {0}; string::reverse_iterator itA = a.rbegin(); string::reverse_iterator itB = b.rbegin(); int index = N - 2; short c = 0; short s = 0; while (c > 0 || itA != a.rend() || itB != b.rend()) { s = 0; if (itA != a.rend()) { s += *itA - '0'; itA++; } if (itB != b.rend()) { s += *itB - '0'; itB++; } s += c; res[index] = s % 10 + '0'; c = s / 10; index--; } char *result = new char[N - index]; strcpy(result, res + index + 1); return result; } int main() { string a, b; cin >> a >> b; char* str = add(a, b); printf("%s", str); delete str; return 0; }
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 | #include <iostream> #include <string.h> using namespace std; char* add(string a, string b) { const int N = 5005; char res[N] = {0}; string::reverse_iterator itA = a.rbegin(); string::reverse_iterator itB = b.rbegin(); int index = N - 2; short c = 0; short s = 0; while (c > 0 || itA != a.rend() || itB != b.rend()) { s = 0; if (itA != a.rend()) { s += *itA - '0'; itA++; } if (itB != b.rend()) { s += *itB - '0'; itB++; } s += c; res[index] = s % 10 + '0'; c = s / 10; index--; } char *result = new char[N - index]; strcpy(result, res + index + 1); return result; } int main() { string a, b; cin >> a >> b; char* str = add(a, b); printf("%s", str); delete str; return 0; } |