leetcode-43-multiply-strings

题目描述:

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

示例:

1
2
3
4
5
6
7
8
示例 1:

输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:

输入: num1 = "123", num2 = "456"
输出: "56088"

说明:

  • num1 和 num2 的长度小于110。
  • num1 和 num2 只包含数字 0-9。
  • num1 和 num2 均不以零开头,除非是数字 0 本身。
  • 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。

Solution 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
num1 = num1[::-1]
num2 = num2[::-1]
l1, l2 = len(num1), len(num2)
res = []
for i in range(l1+l2):
res.append('0')
for i in range(l1):
for j in range(l2):
tmp = int(num1[i]) * int(num2[j])
carry = int(res[i+j]) + tmp % 10
res[i+j] = str(carry % 10)
res[i+j+1] = str(int(res[i+j+1]) + tmp // 10 + carry // 10)
res = res[::-1]
for i in range(l1+l2):
if res[i] != '0':
break
return ''.join(res[i:])

Solution 2 (小改动较Solution 1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
num1 = num1[::-1]
num2 = num2[::-1]
l1, l2 = len(num1), len(num2)
res = [0] * (l1 + l2)
for i in range(l1):
for j in range(l2):
tmp = int(num1[i]) * int(num2[j])
carry = int(res[i+j]) + tmp % 10
res[i+j] = carry % 10
res[i+j+1] = int(res[i+j+1]) + tmp // 10 + carry // 10
res = res[::-1]
for i in range(l1+l2):
if res[i] != 0:
break
return ''.join(map(str, res)[i:])