LeetCode 2: Add Two Numbers题解(Python)
程序员文章站
2022-05-30 22:51:48
Leetcode 2: Add Two Numbers分类:Linked List难度:Midium (M-)描述: 给两个链表(linked list),链表元素是int形式,求两个链表代表的数的和Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8Explanation: 342 + 465 = 807.链接: Add Two Numbers思路:此题稍微麻烦之处在于要用linked lis...
Leetcode 2: Add Two Numbers
分类:Linked List
难度:Midium (M-)
描述: 给两个链表(linked list),链表元素是int形式,求两个链表代表的数的和
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
链接: Add Two Numbers
思路:
此题稍微麻烦之处在于要用linked list做数学运算。那么直接模拟数学运算即可。需要注意的点是进位问题。这里可以使用一个carry来存储进位位。比方说5+8=13,进一位,carry = (5+8)//10 = 1
除此之外,如果进位在最后一位,可以把res.next
指向carry
即可:res.next = ListNode(carry)
. 代码如下:
# 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:
if not l1 and not l2:
return None
result = ListNode() #ListNode(None)
res = result
carry = 0 '''承载进位位'''
while l1 or l2:
val1, val2 = 0, 0
if l1:
val1 = l1.val
l1 = l1.next
if l2:
val2 = l2.val
l2 = l2.next
ans = carry + val1 + val2
carry = ans//10
res.next = ListNode(ans%10)
res = res.next
if carry > 0: '''如果到了末尾,进位位不为0,需要连接到res链表尾部'''
res.next = ListNode(carry)
return result.next
个人总结:
1)此题不难,但是考验基本功
2)链表相关问题,在return时候是return链表还是链表.next,在其他的linked list问题中需要注意
本文地址:https://blog.csdn.net/Bourns_A/article/details/107335089
下一篇: 支持月付的美国虚拟主机
推荐阅读
-
leetcode 2. Add Two Numbers
-
Leetcode--Add Two Numbers(0002)
-
Leetcode 2. Add Two Numbers (java)
-
2. Add Two Numbers
-
LeetCode 2: Add Two Numbers题解(Python)
-
Leetcode--Add Two Numbers(0002)
-
leetcode 2. Add Two Numbers
-
【小白爬Leetcode2】1.10 两数相加Add Two Numbers
-
Leetcode 2. Add Two Numbers (java)
-
2. Add Two Numbers