Advertisement
Josif_tepe

Untitled

Feb 22nd, 2024
942
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. string add_two_numbers(string a, string b) {
  5.     if((int) b.size() > (int) a.size()) {
  6.         swap(a, b);
  7.     }
  8.     int carry = 0;
  9.     string res = "";
  10.     int i = (int) a.size() - 1, j = (int) b.size() - 1;
  11.     while(j >= 0) {
  12.         int digit_a = (int) (a[i] - '0');
  13.         int digit_b = (int) (b[j] - '0');
  14.         int sum = digit_a + digit_b + carry;
  15.         if(sum < 10) {
  16.             res += (sum + '0');
  17.         }
  18.         else {
  19.             carry = 1;
  20.             res += ((sum % 10) + '0');
  21.         }
  22.         i--;
  23.         j--;
  24.     }
  25.     while(i >= 0) {
  26.         int digit_a = (int) (a[i] - '0');
  27.         int sum = digit_a + carry;
  28.         if(sum < 10) {
  29.             carry = 0;
  30.             res += (sum + '0');
  31.         }
  32.         else {
  33.             carry = 1;
  34.             res += ((sum % 10) + '0');
  35.         }
  36.         i--;
  37.     }
  38.     if(carry == 1) {
  39.         res += "1";
  40.     }
  41.     reverse(res.begin(), res.end());
  42.     return res;
  43. }
  44. int main() {
  45.     ios_base::sync_with_stdio(false);
  46.     cout << add_two_numbers("999", "999");
  47.     return 0;
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement