题目
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.
题目要求
给定两个用字符串表示的数字,进行乘法运算,并且返回结果用字符串表示。
解题思路
先将两个数字字符串进行反转,使得低位在前,然后根据乘法法则逐位相乘,并将结果先累加到相应位置上,然后对逐位乘的结果按位从低位到高位取模,进位。最后返回时要先去掉高位可能存在的0。
代码
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
# make sure size of num2 is bigger than size of num1
if len(num1) > len(num2):
return self.multiply(num2,num1)
num1 = num1[::-1]
num2 = num2[::-1]
ans = [0] * (len(num1) + len(num2))
for i in range(len(num1)):
for j in range(len(num2)):
ans[i + j] += int(num1[i]) * int(num2[j])
c = 0
for i in range(len(ans)):
ans[i] += c
ans[i],c = ans[i] % 10, ans[i] / 10
while c > 0:
ans.append(c % 10)
c = c / 10
index = len(ans) - 1
while index > 0 and ans[index] == 0:
index -= 1
return ''.join([str(x) for x in ans[0:index + 1]][::-1])