LeetCode 热题 HOT 100之两数相加
题目2:给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
方案:模拟人类做加法的过程,让相同位上两个数相加再加上进位,mol10后是当前位的值,整除10后的值作为进位。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ans = curr = ListNode()
carry = 0
while (l1 or l2):
n1 = l1.val if l1 else 0
n2 = l2.val if l2 else 0
summ = n1 + n2 + carry
curr.next = ListNode(summ % 10)
carry = summ // 10
if l1: l1 = l1.next
if l2: l2 = l2.next
curr = curr.next
if carry:
curr.next = ListNode(carry)
return ans.next
另一种相似的方法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
ans = curr = ListNode()
carry = 0
while (l1 or l2):
if l1 and l2:
summ=(l1.val+l2.val)+carry
l1=l1.next
l2=l2.next
elif l1:
summ=l1.val+carry
l1=l1.next
else:
summ=l2.val+carry
l2=l2.next
curr.next=ListNode(summ%10)
carry=summ//10
curr=curr.next
if carry:
curr.next = ListNode(carry)
return ans.next
来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。