题目简介
原文: 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
译: 有两个包含非负整数的链表,这两个链表也是非空的。数字倒序存储并且它们每个节点包含一个数字。分别对两个链表的每个数字相加,并将结果存在一个链表中返回。
你可以假设两个链表中不包含任何前导零(leading zero),数字0除外。
Swift (version 3.1):
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var sum = 0
var result:ListNode? = ListNode(0)
var sums = result
var temp1 = l1
var temp2 = l2
while temp1 != nil || temp2 != nil || sum != 0 {
if temp1 != nil {
sum += temp1!.val
temp1 = temp1?.next
}
if temp2 != nil {
sum += temp2!.val
temp2 = temp2?.next
}
sums?.next = ListNode(sum % 10)
sums = sums?.next
sum = sum/10
}
return result?.next
}复制代码
Python (version 3.5):
def addTwoNumbers(self, l1, l2):
result = temp = ListNode(0)
sum = 0
while l1 or l2 or sum:
if l1:
sum += l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
temp.next = ListNode(sum%10)
temp = temp.next
sum = sum/10
return result.next复制代码