Question
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.
Hide Tags Math String
Hide Similar Problems (M) Add Two Numbers (E) Plus One (E) Add Binary
Solution
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if len(num1)==0 or len(num2)==0 or num1=='0' or num2=='0':
return '0'
num1, num2 = list(num1), list(num2)
num1.reverse()
num2.reverse()
res = [0]*(len(num1)+len(num2))
for ind1 in range(len(num1)):
a = ord(num1[ind1]) - ord('0')
for ind2 in range(len(num2)):
b = ord(num2[ind2]) - ord('0')
res[ind1+ind2] += a*b
ress = []
carry = 0
for ind in range(len(res)):
digit = res[ind]%10
ress = [(digit+carry)%10] + ress
carry = res[ind]/10 + (digit+carry)/10
if len(ress)>0 and ress[0]==0:
ress = ress[1:]
ress = [str(elem) for elem in ress]
ress = ''.join(ress)
return ress