class Solution(object):
def multiply(self, num1, num2):
num1 = num1[::-1]
num2 = num2[::-1]
length1 = len(num1)
length2 = len(num2)
temp = [0] * (length1 + length2)
for i in range(length1):
for j in range(length2):
temp[i+j] += int(num1[i]) * int(num2[j])
result = []
for i, num in enumerate(temp):
digit = num % 10
carry = num / 10
result.insert(0, str(digit))
if i < length1 + length2 - 1:
temp[i+1] += carry
while result[0] == '0' and len(result) > 1: # "9133" * "0"
result.pop(0)
return "".join(result)
測(cè)試
if __name__ == "__main__":
s = Solution()
inputs = [["982","125"], ["12345","567"], ["12345","0"], ["0","0"], ["0","567"]]
outputs = ["122750", "6999615", "0", "0", "0"]
for i in range(len(inputs)):
print s.multiply(inputs[i][0], inputs[i][1]) == outputs[i]
True
True
True
True
True