43. Multiply Strings

Problem statement:

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

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

Solution:

This problem is a math related question. The following figures give a very brief explanation about how to match the digits multiplication to the final result.

We should loop from the back of two strings, this pattern follows the multiplication rules. Suppose the two digits form num1 is i and num2 is j, the final position in multiplication is i + j and i + j + 1. We need to update the mul[i + j + 1] by addition and mul[i + j + 1] by carry.

We should think carefully about the corner case.

  1. leading zero.
  2. For the test case, such as "999", "0", if we ignore the leading zero, the return string is "". When return value, do this test.

Time complexity is O(m * n).

class Solution {
public:
    string multiply(string num1, string num2) {
        string mul_str;
        vector<int> mul(num1.size() + num2.size(), 0);
        for(int i = num1.size() - 1; i >= 0; i--){
            for(int j = num2.size() - 1; j >= 0; j--){
                int dig_mul = (num1[i] - '0') * (num2[j] - '0') + mul[i + j + 1];
                mul[i + j + 1] = dig_mul % 10;
                mul[i + j] += dig_mul / 10;
            }
        }
        for(auto digit : mul){
            if(!(digit == 0 && mul_str.empty())) {
                mul_str.push_back(digit + '0');
            }
        }
        return mul_str.empty() ? "0" : mul_str;
    }
};
原文地址:https://www.cnblogs.com/wdw828/p/6876896.html