LeetCode算法--2、Add Two Numbers

本文介绍了一种使用链表实现加法的方法。通过遍历两个非空链表,这些链表代表了非负整数,其数字按逆序存储。文章提供了两种实现方式,并详细解释了每一步的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

我的写法是:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        carry = 0 #表示是否有进位
        start = l1 #指针起始位置
        pre = None #计算的前一个节点
        while (l1 != None) and (l2 != None):
            sum = l1.val + l2.val + carry #计算位数的和
            #判断该位数计算和之后是否需要向下一位进位
            if sum >= 10:
                l1.val = sum - 10
                carry = 1
            else:
                l1.val = sum
                carry = 0

            pre = l1
            l1 = l1.next
            l2 = l2.next

        #当两个链表长度不一致时的处理
        #1、当链表2比链表1长时
        if(l2 != None):
            pre.next = l2
            #将l1指向l2剩下的节点进行处理
            l1 = pre.next

        #2、当链表1比链表2长时的处理
        #此时链表2的指针指向末尾,所以只需要判断是否存在进位即可得出两数之和
        while l1 != None:
            if carry == 1:
                if l1.val==9:
                    l1.val = 0
                    carry = 1
                else:
                    l1.val += 1
                    carry = 0
            pre = l1
            l1 = l1.next

        #此时两个链表已经计算完毕,只需要判断最后的计算结果是否需要添加新节点存储
        if carry == 1:
            pre.next = ListNode(1)

        return start

大神的写法是:

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        carry = 0
        root = n = ListNode(0)
        while l1 or l2 or carry:
            v1 = v2 = 0
            if l1:
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            carry, val = divmod(v1+v2+carry, 10)
            n.next = ListNode(val)
            n = n.next
        return root.next


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值