Advertisement
Guest User

Untitled

a guest
Dec 30th, 2017
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.17 KB | None | 0 0
  1. // C++ program to multiply two numbers represented
  2. // as strings.
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // Multiplies str1 and str2, and prints result.
  7. string multiply(string num1, string num2)
  8. {
  9.     int n1 = num1.size();
  10.     int n2 = num2.size();
  11.     if (n1 == 0 || n2 == 0)
  12.        return "0";
  13.  
  14.     // will keep the result number in vector
  15.     // in reverse order
  16.     vector<int> result(n1 + n2, 0);
  17.  
  18.     // Below two indexes are used to find positions
  19.     // in result.
  20.     int i_n1 = 0;
  21.     int i_n2 = 0;
  22.  
  23.     // Go from right to left in num1
  24.     for (int i=n1-1; i>=0; i--)
  25.     {
  26.         int carry = 0;
  27.         int n1 = num1[i] - '0';
  28.  
  29.         // To shift position to left after every
  30.         // multiplication of a digit in num2
  31.         i_n2 = 0;
  32.          
  33.         // Go from right to left in num2            
  34.         for (int j=n2-1; j>=0; j--)
  35.         {
  36.             // Take current digit of second number
  37.             int n2 = num2[j] - '0';
  38.  
  39.             // Multiply with current digit of first number
  40.             // and add result to previously stored result
  41.             // at current position.
  42.             int sum = n1*n2 + result[i_n1 + i_n2] + carry;
  43.  
  44.             // Carry for next iteration
  45.             carry = sum/10;
  46.  
  47.             // Store result
  48.             result[i_n1 + i_n2] = sum % 10;
  49.  
  50.             i_n2++;
  51.         }
  52.  
  53.         // store carry in next cell
  54.         if (carry > 0)
  55.             result[i_n1 + i_n2] += carry;
  56.  
  57.         // To shift position to left after every
  58.         // multiplication of a digit in num1.
  59.         i_n1++;
  60.     }
  61.  
  62.     // ignore '0's from the right
  63.     int i = result.size() - 1;
  64.     while (i>=0 && result[i] == 0)
  65.        i--;
  66.  
  67.     // If all were '0's - means either both or
  68.     // one of num1 or num2 were '0'
  69.     if (i == -1)
  70.        return "0";
  71.  
  72.     // generate the result string
  73.     string s = "";
  74.     while (i >= 0)
  75.         s += std::to_string(result[i--]);
  76.  
  77.     return s;
  78. }
  79.  
  80. // Driver code
  81. int main()
  82. {
  83.     string str1 = "1235421415454545454545454544";
  84.     string str2 = "1714546546546545454544548544544545";
  85.     cout << multiply(str1, str2);
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement