代码改变世界

[LeetCode] 43. Multiply Strings_Medium tag: string

2021-08-08 00:02  Johnson_强生仔仔  阅读(27)  评论(0编辑  收藏  举报

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

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

 

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

 

Constraints:

  • 1 <= num1.length, num2.length <= 200
  • num1 and num2 consist of digits only.
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.

Ideas:

1. 建一个helper function来得到num1 * onedigit.

2. 对于每个num2的digit,分别加上它的times

3. 最后相加得到结果

 

有两个code,第一个是直接利用int去将string转换为integer,如果题目不允许的话,那就看第二个code,将int(digit)  => ord(digit) - ord('0') 即可

 

Code1: 利用int()

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        if '0' in [num1, num2]: return '0'
        times, finalSum = 1, 0
        for i in range(len(num2) - 1, -1, -1):
            finalSum += self.multiplyOneDigit(num1, num2[i]) * times
            times *= 10
        return str(finalSum)
    
    # multiplyOne
    def multiplyOneDigit(self, num1, singleDigit) -> int:
        if singleDigit == '0':
            return 0
        times, curSum = 1, 0
        for i in range(len(num1) - 1, -1, -1):
            curSum += int(num1[i]) * int(singleDigit) * times
            times *= 10
        return curSum
    

 

 

Code2: 利用ord() 去代替int()

class Solution:
    def multiply(self, num1: str, num2: str) -> str:
        if '0' in [num1, num2]: return '0'
        times, finalSum = 1, 0
        for i in range(len(num2) - 1, -1, -1):
            finalSum += self.multiplyOneDigit(num1, num2[i]) * times
            times *= 10
        return str(finalSum)
    
    # multiplyOne
    def multiplyOneDigit(self, num1, singleDigit) -> int:
        if singleDigit == '0':
            return 0
        times, curSum = 1, 0
        for i in range(len(num1) - 1, -1, -1):
            curSum += (ord(num1[i]) - ord('0')) * (ord(singleDigit) - ord('0')) * times
            times *= 10
        return curSum