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. You may assume the two numbers do not contain any leading zero, except the number 0 itself.
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defaddTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: res = ListNode(0) tmp = res left = 0
while l1 or l2 orleft: left, right = divmod(sum(l and l.val or0for l in (l1, l2)) + left, 10) tmp.next = ListNode(right) tmp = tmp.next l1 = l1 and l1.next l2 = l2 and l2.next