#include <iostream> #include <string> using namespace std; int main() { string a, b; string ans = ""; cin >> a >> b; int i = 0, carry = 0;; string smaller, bigger; if (max(a.length(), b.length()) == a.length()) { smaller = b; bigger = a; i = a.length(); } else { smaller = a; bigger = b; i = b.length(); } i -= 1; int diff = bigger.length() - smaller.length(); int num1, num2; while (i >= 0) { num1 = int(bigger[i] - '0'); num2 = i - diff < 0 ? 0 : int(smaller[i - diff] - '0'); if (i == 0) { ans += to_string((num1 + num2 + carry) % 10); if (num1 + num2 + carry > 9) ans += to_string((num1 + num2 + carry) / 10); break; } ans += to_string((num1 + num2 + carry) % 10); if (num1 + num2 + carry > 9) carry = (num1 + num2 + carry) / 10; i--; } for (int i = ans.length() - 1; i >= 0; i--) cout << ans[i]; cout << '\n'; }
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 | #include <iostream> #include <string> using namespace std; int main() { string a, b; string ans = ""; cin >> a >> b; int i = 0, carry = 0;; string smaller, bigger; if (max(a.length(), b.length()) == a.length()) { smaller = b; bigger = a; i = a.length(); } else { smaller = a; bigger = b; i = b.length(); } i -= 1; int diff = bigger.length() - smaller.length(); int num1, num2; while (i >= 0) { num1 = int(bigger[i] - '0'); num2 = i - diff < 0 ? 0 : int(smaller[i - diff] - '0'); if (i == 0) { ans += to_string((num1 + num2 + carry) % 10); if (num1 + num2 + carry > 9) ans += to_string((num1 + num2 + carry) / 10); break; } ans += to_string((num1 + num2 + carry) % 10); if (num1 + num2 + carry > 9) carry = (num1 + num2 + carry) / 10; i--; } for (int i = ans.length() - 1; i >= 0; i--) cout << ans[i]; cout << '\n'; } |