[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
-------
6 7 6 4

 

如果自己再寫些例子出來,不難發現,兩數相乘得到的乘積的長度其實其實不會超過兩個數字的長度之和,若 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;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/43

 

類似題目:

Add Two Numbers

Plus One

Add Binary

Add Strings 

 

參考資料:

https://leetcode.com/problems/multiply-strings/

https://leetcode.com/problems/multiply-strings/discuss/17605/Easiest-JAVA-Solution-with-Graph-Explanation

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM