题目:
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
思路:
类似加法公式,每次算两个数字的相加,carry保存进位。
先处理l1、l2都有数字的部分;
再处理l1或l2有数字的部分;
最后考虑最高位可能的进位。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
ans = ListNode(0)
finalans = ans
carry = 0 #进位
#l1,l2相应位都有数字
while l1 and l2:
sum2 = l1.val + l2.val + carry
carry = sum2 // 10
ans.next = ListNode(sum2 % 10)
ans = ans.next;
l1 = l1.next; l2 = l2.next
if l1:
ans.next = l1
elif l2:
ans.next = l2
else:
ans.next = None
#l1或l2有数字
while ans.next:
sum2 = ans.next.val + carry
carry = sum2 // 10
ans.next.val = (sum2 % 10)
ans = ans.next
#最高位可能的进位1
if carry is 1:
ans.next = ListNode(1)
return finalans.next