Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
题意分析:
本题是求两个用string表示的非负大数的乘积,乘数可以是任意大小。
解答:
可以用一个临时List表示乘积的每一位,然后对两个乘数每一位两两相乘,并将结果填到相应的List坐标中即可。
AC代码:
class Solution(object): def multiply(self, num1, num2): ret_list = [0] * (len(num1) + len(num2)) for i, vi in enumerate(reversed(num1)): for j, vj in enumerate(reversed(num2)): ret_list[i + j] += int(vi) * int(vj) ret_list[i + j + 1] += ret_list[i + j] / 10 ret_list[i + j] %= 10 while len(ret_list) > 1 and ret_list[-1] == 0: ret_list.pop() return ‘‘.join(map(str, ret_list[::-1]))
时间: 2024-10-10 16:34:49