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 contains a single digit. Add the two numbers and return the sum as a linked list.
您会得到两个非空链接列表,它们代表两个非负整数。这些数字以相反的顺序存储,并且它们的每个节点都包含一个数字。将两个数字相加并返回总和作为链接列表。
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
您可能会假定两个数字除了数字0本身以外都不包含任何前导零。
Example 1:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Example 2:
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3:
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
</pre>
Constraints:
- The number of nodes in each linked list is in the range
[1, 100]
. 0 <= Node.val <= 9
- It is guaranteed that the list represents a number that does not have leading zeros.
Solution:
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
dummy = ListNode(0)
p = dummy
while l1 and l2:
p.next = ListNode((l1.val + l2.val + carry) % 10)
carry = (l1.val + l2.val + carry) // 10
l1 = l1.next
l2 = l2.next
p = p.next
#consider the length of l1 and l2 are different
#l1: 1 -> 2 -> 3
#l2: 6 -> 7 -> 8 -> 9
if l2:
while l2:
p.next = ListNode((l2.val + carry) % 10)
carry = (l2.val + carry) // 10
l2 = l2.next
p = p.next
if l1:
while l1:
p.next = ListNode((l1.val + carry) % 10)
carry = (l1.val + carry) // 10
l1 = l1.next
p = p.next
#consider if the sum of first digit will exceed 10
if carry == 1:
p.next = ListNode(1)
return dummy.next
We need to consider carry when calculating each digit and the situation where l1 and l2 may have different length. We will need to check the remaining of either l1 or l2 (depends on which one is longer). Finally, don't forget to add 1 more digit if the last digit we calculate exceeds 9.
在计算每个数字时,我们需要考虑进位,以及l1和l2可能具有不同长度的情况。我们将需要检查l1或l2的其余部分(取决于哪一个更长)。最后,如果我们计算的最后一位数字超过9,不要忘了再增加1位数字。