两数相加
题目描述:
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
num1 = 0
num2 = 0
len1 = self.getlen(l1)
len2 = self.getlen(l2)
for i in range(len1):
num1 += (l1.val*(10**i))
l1 = l1.next
for i in range(len2):
num2 += (l2.val*(10**i))
l2 = l2.next
num = num1 + num2
LNode = ListNode(num%10)
num = int(num/10)
temp = LNode
while num > 0:
temp.next = ListNode(num%10)
temp = temp.next
num = int(num / 10)
return LNode
def getlen(self,l):
i = 0
while l != None:
l = l.next
i+=1
return i
思路:常规解法,将链表转成数字计算之后再转换为链表
class Solution(object):
def addTwoNumbers(self, l1, l2):
i = int((l1.val + l2.val) / 10)
LNode = ListNode((l1.val + l2.val) % 10)
temp = LNode
l1 = l1.next
l2 = l2.next
while l1 is not None or l2 is not None:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
temp.next = ListNode((val1+val2+i)%10)
i = int((i + val1+val2) / 10)
temp = temp.next
l1=l1.next if l1 else None
l2=l2.next if l2 else None
if not i == 0:
temp.next = ListNode(i)
temp = temp.next
return LNode
思路:不进行转化直接进行计算,l1,l2同时为None时才结束循环,i表示进位数
例如l1.val = 9 l2.val = 9 时,编入新链表的节点值为8,i = 1
当整个循环结束时,需要判断i是否为0,若不为0则还需增加一个值为i的新节点