Multiply Strings in C++



We have given two strings consisting of integers and can have lengths up to 200. both strings do not contain any leading 0, but 0 as the number itself can be present. We have to multiply integer strings, so we need to find a solution. Let's see how we can tackle this problem in an easier way.

Suppose we have two numbers as strings. We need to multiply them and return the result, also in a string. For example, if the numbers are "26" and "12", then the result will be "312". Following are various ways to multiply strings in C++.

Using the still() Method

In this section, we will see how to multiply two strings in C++ using a built-in method. Although this is not an efficient approach. because the large size integer can cause potential overflow but we are still covering this approach to provide a complete understanding of this method.

Below is the code for Multiplying two strings in C++ using stoll()

#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
   string multiply(string num1, string num2) {
   long long n1 = stoll(num1);
   long long n2 = stoll(num2);
   long long res = n1 * n2;
   return to_string(res);
   }
};
int main() {
   Solution sol;
   cout << sol.multiply("123", "456") << endl;  // Output: 56088
   return 0;
}

Time Complexity: O(1)

Space Complexity: O(1)

Explanation

In this solution, given two strings, num1, and num2, we need to convert them into integers. For this purpose, initialize two long variables, n1, and n2, and assign them the integer values of the strings num1 and num2, respectively. Then, store the multiplication result of n1 and n2 in a long long variable named res and return it in the form of a string.

Note: This approach doesn't work for large input

By Multiplying Each Digit

To solve this, we will follow these steps:

  • Initialize the result string ans with length m + n where m is the length of 1st given string and n is the length of 2nd given string, and assign '0' as value code.
  • Loop through num1 and num2 string from right to left. and for each num1 digit multiply it by each num2 digit.
  • Add the multiplication result from the previous step to ans at the appropriate place.
  • Adjust for carries, if a carry is present add it to the next higher position in a string
  • Remove the leading 0 from a string if leading zeros are present.
  • Return the ans string at last. if ans string only consist 0. then, return "0".

Below is an example code to solve the multiply two strings problem in C++:

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string multiply(string num1, string num2);
};
string Solution::multiply(string nums1, string nums2) {
   int n = nums1.size();
   int m = nums2.size();
   string ans(n + m, '0');
   for(int i = n - 1; i >= 0; i--) {
      for(int j = m - 1; j >= 0; j--) {
         int p = (nums1[i] - '0') * (nums2[j] - '0') + (ans[i + j + 1] - '0');
         ans[i+j+1] = p % 10 + '0';
         ans[i+j] += p / 10;
   }
}
   for(int i = 0; i < m + n; i++) {
      if(ans[i] !='0') return ans.substr(i);
   }
   return "0";
   }
int main() {
   Solution ob;
   cout << ob.multiply("28", "25");
   return 0;
}

Time Complexity: O(n * m)

Space Complexity: O(n + m)

Explanation:

In this example code we are looping num1 and num2 strings from right to left and multiplying the last digits of both strings storing the product in ans and preserving carry in ans's next position. and adding it to the next-digit product. Finally, we are returning the ans

Karatsuba Multiplication Algorithm

To solve this, we will follow these steps:

  • Split the given numbers into two halves. For x and y, let x split into x1 and x0, and y split into y1 and y0.
  • Calculate three products using recursion:
    • A = multiply(x1, y1)
    • B = multiply(x0, y0)
    • C = multiply(x1 + x0, y1 + y0) - A - B
  • Combine the results using the following formula:
    • result = A * 10^2m + C * 10^m + B
  • Finally, return the combined result.

Following is an example -

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
   string multiply(string x, string y);
private:
   string karatsuba(string x, string y);
   string add(string a, string b);
   string sub(string a, string b);
   string mulSingle(char x, char y);
};

string Solution::multiply(string x, string y) {
   return karatsuba(x, y);
}

string Solution::karatsuba(string x, string y) {
   int n = max(x.size(), y.size());
   if (n == 0) return "0";
   if (n == 1) return mulSingle(x[0], y[0]);

   // Ensure both numbers have the same length
   while (x.size() < n) x = '0' + x;
   while (y.size() < n) y = '0' + y;

   int half = n / 2;
   string x1 = x.substr(0, half);
   string x0 = x.substr(half);
   string y1 = y.substr(0, half);
   string y0 = y.substr(half);

   string A = karatsuba(x1, y1);
   string B = karatsuba(x0, y0);
   string C = karatsuba(add(x1, x0), add(y1, y0));
   C = sub(C, add(A, B));

   return add(add(A + string(2 * (n - half), '0'), C + string(n - half, '0')), B);
}

string Solution::add(string a, string b) {
   int carry = 0;
   string res = "";
   int i = a.size() - 1, j = b.size() - 1;
   while (i >= 0 || j >= 0 || carry) {
      int sum = carry;
      if (i >= 0) sum += a[i--] - '0';
      if (j >= 0) sum += b[j--] - '0';
      carry = sum / 10;
      res += (sum % 10) + '0';
   }
   reverse(res.begin(), res.end());
   return res;
}

string Solution::sub(string a, string b) {
   // Assumes a >= b
   int borrow = 0;
   string res = "";
   int i = a.size() - 1, j = b.size() - 1;
   while (i >= 0 || j >= 0 || borrow) {
      int diff = (i >= 0 ? a[i--] - '0' : 0) - (j >= 0 ? b[j--] - '0' : 0) - borrow;
      if (diff < 0) {
         diff += 10;
         borrow = 1;
      } else {
         borrow = 0;
      }
      res += diff + '0';
   }
   reverse(res.begin(), res.end());
   return res;
}

string Solution::mulSingle(char x, char y) {
   return to_string((x - '0') * (y - '0'));
}

int main() {
   Solution ob;
   cout << ob.multiply("1234", "5678");
}

Time Complexity: O(n^1.585)

Space Complexity: O(1)

Explanation:

In this example code, we are splitting each number into two halves and then calculating three products using recursion: A, B, and C. Then we combine these products to get the final result using the formula provided. This approach reduces the complexity of multiplication by breaking it into smaller problems and makes it more efficient for large numbers.

Updated on: 2024-11-11T15:46:46+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements