Leetcode 第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.
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.
题目大意: 给你两个数字,用链表连接每一位并且倒序连接。 计算出用链表表示的正序链表。
这道题需要考虑两个地方:
- 链表如何连接。
- 加满进位的问题。
思路一:
暴力解法: 直接编程字符串进行加减,再构造回链表。
这里我学会了,原来Leetcode可以直接用node表示当前节点。以及构造链表的公式如下。
for i in range(1, len(add)):
node = ListNode(add[i])
head.next = node
head = head.next
直接上代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
num1 = ''
num2 = ''
while l1:
num1 += str(l1.val)
l1 = l1.next
while l2:
num2 += str(l2.val)
l2 = l2.next
add = str(int(num1[::-1]) + int(num2[::-1]))[::-1]
head = ListNode(add[0])
res = head
for i in range(1,len(add)):
node = ListNode(add[i])
head.next = node
head = head.next
return res
思路二:
进位用 divmod()表示。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
res = n = ListNode(0)
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
carry, val = divmod(carry, 10)
n.next = n = ListNode(val)
return res.next
终于开始刷medium的了。
疫情中的英国,儿童节?
加油!
01/06/2020