题目描述
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.
代码 (Python3)
class Solution:
def multiply(self, num1: str, num2: str) -> str:
ans = '0'
cnt = 0
for i in range(len(num1) - 1, -1, -1):
temp = '0'
for j in range(int(num1[i])):
temp = self.str_add(temp, num2)
for i in range(cnt):
temp += '0'
print(temp, 123)
cnt += 1
ans = self.str_add(temp, ans)
if ans.startswith('0'):
return '0'
return ans
def str_add(self, s1, s2): # 定义两个字符串的加法运算
jw = 0
if len(s2) > len(s1):
s1, s2 = self.swap(s1, s2)
s1 = list(s1)
s2 = list(s2)
i = len(s1) - 1
j = len(s2) - 1
while i >= 0 and j >= 0:
now = int(s1[i]) + int(s2[j]) + jw
jw = now // 10
s1[i] = str(now % 10)
i -= 1
j -= 1
if jw and len(s1) == len(s2):
s1.insert(0, '1')
elif jw:
while i >= 0:
now = int(s1[i]) + jw
jw = now // 10
s1[i] = str(now % 10)
i -= 1
if jw:
s1.insert(0, '1')
return "".join(s1)
def swap(self, s1, s2):
temp = s1
s1 = s2
s2 = temp
return s1, s2