LeetCode 43. Multiply Strings
考点 | 难度 |
---|---|
Math | Medium |
题目
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.
思路
num1
和num2
从后向前,相乘的结果加到i + j
位,进位加到i + j + 1
位,最后i + j
位保留个位数。res[i+j+1] += res[i+j]//10
用+=
是因为列竖式做乘法的时候总是两个两个相加,之前留下来的i + j
位和新算出来的i + j
位加起来需要大于10的情况需要考虑进位。
答案
class Solution:
def multiply(self, num1, num2):
res = [0]* (len(num1) + len(num2))
for i, e1 in enumerate(reversed(num1)):
for j, e2 in enumerate(reversed(num2)):
res[i+j] += int(e1) * int(e2)
res[i+j+1] += res[i+j]//10
res[i+j] %= 10
while len(res) > 1 and res[-1] == 0: res.pop()
return ''.join( map(str,res[::-1]) )