https://leetcode.com/problems/add-two-numbers/css
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.html
You may assume the two numbers do not contain any leading zero, except the number 0 itself.node
Example:python
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
(a // b, a % b)
.1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: 9 dummy_head = ListNode( 0 ) 10 p_current = dummy_head 11 carry = 0 12 13 while l1 or l2: 14 val = carry 15 16 if l1: 17 val += l1.val 18 l1 = l1.next 19 20 if l2: 21 val += l2.val 22 l2 = l2.next 23 24 # carry, val = divmod( val, 10 ) 25 carry = val // 10 26 val = val % 10 27 28 p_current.next = ListNode( val ) # use next node to store current sum result, otherwise there will be an extra node of 0 on the tail 29 30 p_current = p_current.next 31 32 if carry == 1: 33 p_current.next = ListNode( 1 ) 34 35 return dummy_head.next