当前位置: 移动技术网 > IT编程>脚本编程>Python > LeetCode 2: Add Two Numbers题解(Python)

LeetCode 2: Add Two Numbers题解(Python)

2020年07月16日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网