minty_Brit666‘s python practice no.2

本文详细解析了如何用Python实现LeetCode上的两数相加问题,通过链表结构处理非负整数,并给出了完整代码。算法涉及链表操作、进位处理,适合提升编程技巧。

minty_Brit666

Today’s blog is about the practice of the leetcode.
And I’ll give my own answer in this blog.

You are given two non-empty linked lists representing two non-negative integers. Each digit is stored in reverse order, and only one digit can be stored per node. You add the two numbers and return a linked list representing the sum in the same form. You can assume that neither of these numbers will start with 0, except for the number 0.

Source: LeetCode
Link: https://leetcode-cn.com/problems/add-two-numbers
Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# Create a head node with the value of None, sum and a to point to, sum to return last, and a to traverse
sum = a = ListNode(None)
x = 0 # Initialize carry s to 0
while l1 or l2 or x:
# If l1 or L2 is present, take the value of L1 + the value of l2 + x(x is initially 0, if there is a carry 1 below, add it next time)
x += (l1.val if l1 else 0) + (l2.val if l2 else 0)
a.next = ListNode(x % 10)
# a.next points to the new list to create a new list
a = a.next
#a traverses backwards
x //= 10
# In the case of carry, take the modulus, eg. x = 12, 12 // 10 = 1
l1 = l1.next if l1 else None
#If l1 is present, it is traversed backwards, otherwise None
l2 = l2.next if l2 else None
# If L2 exists, it is traversed backwards, otherwise None
return sum.next
# Returns the next node of sum, since sum points to an empty head node, which is the next node in the new list
Screen Shot 2

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        sum = a = ListNode(None)          
        x = 0
        while l1 or l2 or x:
            x += (l1.val if l1 else 0) + (l2.val if l2 else 0)  
            a.next = ListNode(x % 10)
            a = a.next
            x //= 10
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
        return sum.next

The solution is derived from LeetCode user Mengzhihen.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值