SHARE
TWEET

Untitled

a guest Oct 18th, 2019 80 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. // Function for finding sum of larger numbers
  5. string findSum(string str1, string str2)
  6. {
  7.     // Before proceeding further, make sure length
  8.     // of str2 is larger.
  9.     if (str1.length() > str2.length())
  10.         swap(str1, str2);
  11.  
  12.     // Take an empty string for storing result
  13.     string str = "";
  14.  
  15.     // Calculate length of both string
  16.     int n1 = str1.length(), n2 = str2.length();
  17.  
  18.     // Reverse both of strings
  19.     reverse(str1.begin(), str1.end());
  20.     reverse(str2.begin(), str2.end());
  21.  
  22.     int carry = 0;
  23.     for (int i=0; i<n1; i++)
  24.     {
  25.         // Do school mathematics, compute sum of
  26.         // current digits and carry
  27.         int sum = ((str1[i]-'0')+(str2[i]-'0')+carry);
  28.         str.push_back(sum%10 + '0');
  29.  
  30.         // Calculate carry for next step
  31.         carry = sum/10;
  32.     }
  33.  
  34.     // Add remaining digits of larger number
  35.     for (int i=n1; i<n2; i++)
  36.     {
  37.         int sum = ((str2[i]-'0')+carry);
  38.         str.push_back(sum%10 + '0');
  39.         carry = sum/10;
  40.     }
  41.  
  42.     // Add remaining carry
  43.     if (carry)
  44.         str.push_back(carry+'0');
  45.  
  46.     // reverse resultant string
  47.     reverse(str.begin(), str.end());
  48.  
  49.     return str;
  50. }
  51.  
  52. // Driver code
  53. int main()
  54. {
  55.     char str1[100000], str2[100000];
  56.     scanf("%s %s", str1, str2);
  57.     cout << findSum(str1, str2);
  58.     return 0;
  59. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top