1. 程式人生 > >【LeetCode每天一題】Multiply Strings(字符串乘法)

【LeetCode每天一題】Multiply Strings(字符串乘法)

bject 長度 must you n) 空間復雜度 use strong start

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

思路


  這道題和之前做的字符串加法挺相似的,唯一有區別的是,加法和乘法的計算規則不一樣。加法是對應位置相加,只要一次遍歷。而乘法則是需要兩層循環,因為num1中的每一位都需要乘以num2,最後相加得到結果。這就意味著在一定程度上乘法的細節處理更加繁瑣一些。但是只要抓住核心部分最終都能寫出來。時間復雜度為O(n*m)(n,m分別為num1和num2的長度),空間復雜度為O(m+n)。

實現代碼


 1 class Solution(object):
 2     def multiply(self, num1, num2):
 3         """
 4         :type num1: str
 5         :type num2: str
 6         :rtype: str
 7         """
 8         res_list = [0] * (len(num1) + len(num2))   # 存儲最終結果的數組
 9         start = len(res_list)-1                    # 每一次循環相加位置的下標
10
11 for n1 in reversed(num1): # 兩層循環,意思是使用num2中每一位乘以num1中的每一位 12 tempPos = start # 當前循環內的下標,意思是num1個位乘以num2的每一位時,第一位存儲的是個位。 13 for n2 in reversed(num2): 14 res_list[tempPos] += int(n1) * int(n2) # 存儲當前結果 15 res_list[tempPos-1] += res_list[tempPos]/10 #存儲低一位溢出的數 16 res_list[tempPos] %= 10 # 存儲個位的數 17 tempPos -= 1 # 進一位,意思是下一次結果存儲的位置 18 start -= 1 # 19 20 i = 0 21 while i < len(res_list)-1 and res_list[i] == 0: # 去除前面的0, 並且防止最終結果為零的輸出。 22 i += 1 23 24 return ‘‘.join(map(str, res_list[i:])) # 返回字符串

【LeetCode每天一題】Multiply Strings(字符串乘法)