No.2 Add Two Numbers
原题:
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.
题目大意:给出两个链表,存储非负数,两个链表都是按倒序方式存储数字(个位,十位,百位……)要求将两个链表相加并以链表形式返回。
Example 1:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807
Solution one:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
ptr = head
carry = 0
while True:
if l1 != None:
carry += l1.val
l1 = l1.next
if l2 != None:
carry += l2.val
l2 = l2.next
ptr.val = int(carry % 10)
carry = int(carry / 10)
# 运算未结束新建一个节点用于储存答案,否则退出循环
if l1 != None or l2 != None or carry != 0:
ptr.next = ListNode(0)
ptr = ptr.next
else:
break
return head
第一次一直跑不通的原因是上述代码中的carry = int(carry / 10)没有做int强制类型转换,这就导致carry是一个小说,即便是每次除10依旧是小数不是0,导致最后输出结果多出很多0。
Reference solution:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p = dummy = ListNode(-1)
#进位标志,低位有进位时为1,默认为0
carry = 0
#当两个链表的同一位置同时不为空时(即小詹举例的低三位数)
while l1 and l2:
#p.next为指针所指 l1.val为对应的数据
p.next = ListNode(l1.val + l2.val + carry)
#除法和求模运算获取p.next的十位个位
carry = int(p.next.val / 10) #注意必须要做的强制类型转换
p.next.val = int(p.next.val % 10)
p = p.next
l1 = l1.next
l2 = l2.next
res = l1 or l2 #或运算即对应小詹举得高位例子(第四位第五位)
while res:
p.next = ListNode(res.val + carry)
carry = p.next.val / 10
p.next.val %= 10
p = p.next
res = res.next
if carry:
p.next = ListNode(1)
return dummy.next #返回该链表