今天刷leetcode的时候,刷到了一道大数相乘的题目,以前水比赛的时候都是模板或者java。。今天算是第一次写大数相乘的题目了。
链接:https://leetcode-cn.com/problems/multiply-strings/description/
一开始思路很弱智,将一个数从低位开始按位取,乘上另一个数,然后一层一层的叠加起来,结果没错,就是超时了,上一下超时的代码:
#encoding=utf-8
import numpy as np
class Solution(object):
def mul(self, num1, num2, base, length):
c = 0
l = ['0']*300
top = 299 - base
index = len(num1)-1
n2 = int(num2)
while index>=0 or c != 0:
if index >= 0:
l[top] = str((n2*int(num1[index])+c) % 10)
c = (n2*int(num1[index])+c) / 10
elif c != 0:
l[top] = str(c)
c = 0
index -= 1
top -= 1
return l
def add(self, num1, num2, length):
l = ['0']*300
c = 0
top = 299
while top>=0:
l[top] = str((int(num1[top])+int(num2[top])+c)%10)
c = (int(num1[top])+int(num2[top])+c)/10
top -= 1
return l
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if num1 == '0' or num2 == '0':
return '0'
if len(num2) > len(num1):
tmp = num2
num2 = num1
num1 = tmp
length =len(num1) + len(num2) + 1
top = len(num2)-1
base = 0
ans = ['0']*300
while top >= 0:
ans = self.add(ans, self.mul(num1, num2[top], base, length), length)
top -= 1
base += 1
ans_str = ''.join(ans)
index = 0
while index < len(ans_str):
if ans_str[index] != '0':
break
index += 1
return ans_str[index:]
然后才发现,可以一次性全都按位乘出结果,不考虑进位,再一次性处理进位。然后就解决超时问题了。
上个代码:
#encoding=utf-8
import numpy as np
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if num1 == '0' or num2 == '0':
return '0'
length =len(num1) + len(num2) + 1
l = [0] * length
l_1 = list(num1)
l_2 = list(num2)
l_1.reverse()
l_2.reverse()
for i in range(len(l_2)):
for j in range(len(l_1)):
l[i+j] += int(l_2[i])*int(l_1[j])
c = 0
for i in range(length):
tmp = l[i] + c
c = tmp / 10
l[i] = tmp % 10
l.reverse()
ans = []
flag = False
for i in range(length):
if flag == False and l[i] == 0:
continue
else:
flag = True
ans.append(str(l[i]))
return ''.join(ans)