43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

Note:

  1. The length of both num1 and num2 is < 110.

  2. Both num1 and num2 contain only digits 0-9.

  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.

  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

string multiply(string num1, string num2) { // time: O(m * n); space: O(m + n)
    int m = num1.length(), n = num2.length();
    string res(m + n, '0');
    for (int i = m - 1; i >= 0; --i) {
        int carry = 0;
        for (int j = n - 1; j >= 0; --j) {
            int sum = (res[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
            res[i + j + 1] = sum % 10 + '0';
            carry = sum / 10;
        }
        res[i] += carry;
    }
    int startPos = res.find_first_not_of("0");
    return startPos != string::npos ? res.substr(startPos) : "0";
}
string multiply(string num1, string num2) { // time: O(m * n); space: O(m + n)
    string res;
    int m = num1.length(), n = num2.length();
    vector<int> vals(m + n);
    for (int i = m - 1; i >= 0; --i) {
        for (int j = n - 1; j >= 0; --j) {
            int mul = (num1[i] - '0') * (num2[j] - '0');
            int p1 = i + j, p2 = i + j + 1, sum = mul + vals[p2];
            vals[p2] = sum % 10;
            vals[p1] += sum / 10;
        }
    }
    for (int val : vals) {
        if (!res.empty() || val != 0) res.push_back((val + '0'));
    }
    return res.empty() ? "0" : res;
}

Last updated

Was this helpful?