1. 程式人生 > >【LeetCode】137.Multiply Strings

【LeetCode】137.Multiply Strings

題目描述(Medium)

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.

演算法分析

直接將字元轉化為數字很浪費空間,因此將字元轉為陣列儲存;m位數字與n位數字相乘,至多有m+n位。

提交程式碼:

typedef vector<int> bigint;

bigint make_bigint(string s) 
{
    bigint result;
    transform(s.rbegin(), s.rend(), back_inserter(result),
             [](char c){return c - '0';});
    return result;
}

string to_string(bigint num) 
{
    string result;
    transform(find_if(num.rbegin(), prev(num.rend()), 
              [](char c) {return c > '\0';}), num.rend(), back_inserter(result),
              [](char c){return c + '0';});
    return result;
}

bigint operator*(bigint const& x, bigint const& y) 
{
    bigint result(x.size() + y.size(), 0);
    for (int i = 0; i < x.size(); ++i) {
        for (int j = 0; j < y.size(); ++j) {
            result[i + j] += x[i] * y[j];
            result[i + j + 1] +=  result[i + j] / 10;
            result[i + j] = result[i + j] % 10;
        }
    }
    
    return result;
}

class Solution {
public:
    string multiply(string num1, string num2) {
        return to_string(make_bigint(num1) * make_bigint(num2));
    }
};