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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
Solutions:
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 num1 = '' 10 while l1 and l1.val: 11 num1 += str(l1.val) 12 l1 = l1.next 13 num1 = int(num1[::-1]) 14 num2 = '' 15 while l2 and l2.val: 16 num2 += str(l2.val) 17 l2 = l2.next 18 num2 = int(num2[::-1]) 19 sum = str(num1 + num2)[::-1] 20 head = ListNode(sum[0]) 21 tmp = head 22 i = 1 23 while i < len(sum): 24 tmp.next = ListNode(sum[i]) 25 tmp = tmp.next 26 i += 1 27 return head 28 29
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 # 方法二: 递归实现: 7 8 class Solution: 9 def addTwoNumbers(self, l1: ListNode, l2: ListNode, c = 0) -> ListNode: 10 val = l1.val + l2.val + c 11 c = val // 10 12 ret = ListNode(val % 10 ) 13 14 if (l1.next != None or l2.next != None or c != 0): 15 if l1.next == None: 16 l1.next = ListNode(0) 17 if l2.next == None: 18 l2.next = ListNode(0) 19 ret.next = self.addTwoNumbers(l1.next,l2.next,c) 20 return ret 21