提交至leetcode的代码
class Solution(object):
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __init__(self, num=None):
if num:
self.creat(num)
def creat(self, listnum):
head = self.ListNode(listnum[0])
for i in listnum[1:]:
node = self.ListNode(i)
node.next = head
head = node
return head
def addTwoNumbers(self, l1, l2):
l3=0
i=0
while l1 or l2:
if l1 and l2:
l3 += (l1.val+l2.val)*(10**i)
l1, l2 = l1.next,l2.next
i+=1
elif l1 :
l3 += l1.val* (10 ** i)
l1 = l1.next
i += 1
elif l2:
l3 += l2.val * (10 ** i)
l2 = l2.next
i += 1
return self.creat(str(l3))
运行时间:56ms
内存消耗:13.1MB
自我思考与检实现的代码
class Solution(object):
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __init__(self, num=None):
if num:
self.creat(num)
def creat(self, listnum):
head = self.ListNode(listnum[0])
for i in listnum[1:]:
node = self.ListNode(i)
node.next = head
head = node
return head
def addTwoNumbers(self, l1, l2):
l=max(len(l1),len(l2))
l1 = self.creat(l1)
l2 = self.creat(l2)
l3=0
i=0
while l1 or l2:
if l1 and l2:
print(i,'a')
l3 += (l1.val+l2.val)*(10**i)
print(' ',l3,type(l3))
l1, l2 = l1.next,l2.next
i+=1
elif l1 :
print(i,'b')
l3 += l1.val* (10 ** i)
print(' ', l3, type(l3))
l1 = l1.next
i += 1
elif l2:
print(i,'c')
l3 += l2.val * (10 ** i)
print(' ', l3, type(l3))
l2 = l2.next
i += 1
else:
print('gg')
return self.creat(str(l3))
a=Solution()
b=a.addTwoNumbers([2,4,3], [5,6,4,1])