给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
个人感觉根据示例表达不清,题意为两个链表每个链相加形成新链,原因有歧义,感觉是链表内先变成相应数字,再相加后变成链表。
首先贴出通过代码。
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
first = head
count = 0 #判断数位数位是否增大
while l1 != None and l2 !=None:
temp = l1.val + l2.val +count
if temp >=10:
head.next = ListNode(temp %10 )
count = 1
head = head.next
else :
head.next = ListNode(temp)
head = head.next
count = 0
l1 = l1.next
l2 = l2.next
while count !=0:#如果l1 l2 有一个或两个None了最后一个数位进一
if l1 !=None:
if l1.val+1 <10:
head.next = ListNode(l1.val+1)
count -=1
else:
head.next = ListNode(0)# [9,9][1]
head = head.next
l1 = l1.next
elif l2 != None:
if l2.val+1 <10:
head.next = ListNode(l2.val+1)
count -=1
else:
head.next = ListNode(0)
head = head.next
l2 = l2.next
else :
head.next = ListNode(1)
head = head.next
count -=1
if l1 != None:
head.next = l1
if l2 != None :
head.next = l2
return first.next
上个精简的,思想一样
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
L = curs = ListNode(0)
flag = 0
while(l1 or l2 or flag):
val1 = val2 = 0
if(l1):
val1 = l1.val
l1 = l1.next
if(l2):
val2 = l2.val
l2 = l2.next
val = (val1+val2+flag) % 10
flag = (val1+val2+flag) // 10
curs.next = ListNode(val)
curs = curs.next
return L.next
最后对于这个题如果是根据给出的原因也可以这样写(表达不清版)leetcode是死答案,这个版本并不会给步骤分。
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
num = list(str(self.__bianhuan(l1) + self.__bianhuan(l2)))
head = ListNode(0)
first = head
for i in num[::-1]:
head.next= ListNode(int(i))
head = head.next
return first.next
def __bianhuan(self,l):
num = 0
while l != None:
num *= 10
num += l.val
l = l.next
return num