C++實現LeetCode(43.字符串相乘)

[LeetCode] 43. Multiply Strings 字符串相乘

Given two non-negative integers num1 and num2represented 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 libraryor convert the inputs to integer directly.

這道題讓我們求兩個字符串數字的相乘,輸入的兩個數和返回的數都是以字符串格式儲存的,這樣做的原因可能是這樣可以計算超大數相乘,可以不受 int 或 long 的數值范圍的約束,那麼該如何來計算乘法呢,小時候都學過多位數的乘法過程,都是每位相乘然後錯位相加,那麼這裡就是用到這種方法,舉個例子,比如 89 x 76,那麼根據小學的算術知識,不難寫出計算過程如下:

8 9  <- num2

    7 6  <- num1

——-

    5 4

  4 8

  6 3

5 6

——-

如果自己再寫些例子出來,不難發現,兩數相乘得到的乘積的長度其實其實不會超過兩個數字的長度之和,若 num1 長度為m,num2 長度為n,則 num1 x num2 的長度不會超過 m+n,還有就是要明白乘的時候為什麼要錯位,比如6乘8得到的 48 為啥要跟6乘9得到的 54 錯位相加,因為8是十位上的數字,其本身相當於80,所以錯開的一位實際上末尾需要補的0。還有一點需要觀察出來的就是,num1 和 num2 中任意位置的兩個數字相乘,得到的兩位數在最終結果中的位置是確定的,比如 num1 中位置為i的數字乘以 num2 中位置為j的數字,那麼得到的兩位數字的位置為 i+j 和 i+j+1,明白瞭這些後,就可以進行錯位相加瞭,累加出最終的結果。

由於要從個位上開始相乘,所以從 num1 和 num2 字符串的尾部開始往前遍歷,分別提取出對應位置上的字符,將其轉為整型後相乘。然後確定相乘後的兩位數所在的位置 p1 和 p2,由於 p2 相較於 p1 是低位,所以將得到的兩位數 mul 先加到 p2 位置上去,這樣可能會導致 p2 位上的數字大於9,所以將十位上的數字要加到高位 p1 上去,隻將餘數留在 p2 位置,這樣每個位上的數字都變成一位。然後要做的是從高位開始,將數字存入結果 res 中,記住 leading zeros 要跳過,最後處理下 corner case,即若結果 res 為空,則返回 “0”,否則返回結果 res,代碼如下:

class Solution {
public:
    string multiply(string num1, string num2) {
        string res = "";
        int m = num1.size(), n = num2.size();
        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[p1] += sum / 10;
                vals[p2] = sum % 10;
            }
        }
        for (int val : vals) {
            if (!res.empty() || val != 0) res.push_back(val + '0');
        }
        return res.empty() ? "0" : res;
    }
};

到此這篇關於C++實現LeetCode(43.字符串相乘)的文章就介紹到這瞭,更多相關C++實現字符串相乘內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: