Multiply Strings
要点:基本公式就是从低位开始(或者string的高index)两层loop:i,j乘积对应的位置是i+j+1(比如0,0,的位置是1,这里0的位置是进位。另外一定要有高位在0的sense)。
错误点:
- j是下位乘数的index,因为有进位,所以j要超出0,要更新j-=1
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
n1 = len(num1)
n2 = len(num2)
res = [0]*(n1+n2)
if num1=="0" or num2=="0": return "0"
for i in range(n1-1, -1, -1):
# 1. reset
carry = 0
for j in range(n2-1, -1, -1):
d1 = ord(num1[i])-ord('0')
d2 = ord(num2[j])-ord('0')
total = d2*d1+carry+res[i+j+1]
carry = total/10
res[i+j+1] = total%10
j-=1
if carry!=0:
total = res[i+j+1]+carry
res[i+j+1]=total%10
if res[0]==0: del res[0]
resStr = []
for i in range(len(res)):
resStr.append(str(res[i]))
return ''.join(resStr)