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.
思路
经典的题目,但是今天写还是犯了错误,易犯错误如下:
- 当cur1和cur2有一个为null就终止,然后把剩下的续上。这样的问题在于进位,进位有可能进很多位,例如1+99999,正确做法是cur1和cur2都为null才终止,如果其中一边用完了就当成0处理就完事。
- 最后可能会多一个carry为1的要单独加上。例如99+99.
代码
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 == None or l2 == None:
return None
dummy = ListNode(0)
cur = dummy
cur1 = l1
cur2 = l2
carry = 0
while cur1 or cur2:
v1 = cur1.val if cur1 else 0
v2 = cur2.val if cur2 else 0
cur.next = ListNode((v1 + v2 + carry) % 10)
carry = (v1 + v2 + carry) // 10
if cur1:
cur1 = cur1.next
if cur2:
cur2 = cur2.next
cur = cur.next
if carry != 0:
cur.next = ListNode(carry)
cur = cur.next
return dummy.next