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.
给你两个非空链表,表示两个非负整数。 数字以相反的顺序存储,每个节点都包含一个数字。 添加这两个数字并将其作为链接列表返回。
您可以假设这两个数字不包含任何前导零,除了数字0本身。
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
class ListNode:
def __init__(self,x):
self.val = x
self.next = none
class solution:
def addTwoSum(self,l1,l2):
a,b,carry = 0
head = None
last_node = None
while l1 or l2:
if l1:
a = l1.val
l1 = l1.next
if l2:
b = l2.val
l2 = l2.next
sum = a+b+carry
carry,digit = divmod(sum,10)
new_node = ListNode(digit)
if not head:
head = new_node
else:
last_node.next = new_node
last_node = new_node
a = b = 0
if carry!=0:
new_node = ListNode(carry)
last_node.next = new_node
last_node = new_node
return head