Multiply Large Numbers represented as Strings in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that multiplies two strings.

Let's see the steps to solve the problem.

  • Initialise the numbers in string.

  • Initialise a string of length number_one_length + number_two_length.

  • Iterate over the first number from the end.

    • Iterate over the second number from the end.

      • Multiply two digits and add the corresponding previous row digit.

      • Update the previous row digit.

      • Store the carry in the previous index of the result string.

  • Convert the char to digits by adding 0 character to every character in the result.

  • Return the result by ignoring the leading zero.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
string multiplyTwoNumbers(string num1, string num2) {
   if (num1 == "0" || num2 == "0") {
      return "0";
   }
   string product(num1.size() + num2.size(), 0);
   for (int i = num1.size() - 1; i >= 0; i--) {
      for (int j = num2.size() - 1; j >= 0; j--) {
            int n = (num1[i] - '0') * (num2[j] - '0') + product[i + j + 1];
            product[i + j + 1] = n % 10;
            product[i + j] += n / 10;
      }
   }
   for (int i = 0; i < product.size(); i++) {
      product[i] += '0';
   }
   if (product[0] == '0') {
      return product.substr(1);
   }
   return product;
}
int main() {
   string num1 = "34";
   string num2 = "57";
   if((num1.at(0) == '-' || num2.at(0) == '-') && (num1.at(0) != '-' || num2.at(0) != '-')) {
      cout << "-";
   }
   if(num1.at(0) == '-') {
      num1 = num1.substr(1);
   }
   if(num2.at(0) == '-') {
      num2 = num2.substr(1);
   }
   cout << multiplyTwoNumbers(num1, num2) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

1938

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 03-Jul-2021 04:32:29
Advertisements