leetcode 2 add two numbers

本文介绍了一个LeetCode上的经典题目:加两数之和。通过定义链表节点类并实现加法功能,解决两个链表代表的大整数相加的问题。算法考虑了进位情况,并能正确处理不同长度的输入。

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

 leetcode 2 add two numbers

常规数字加法

#2017/03/12
# practise on leetcode

# Definition for singly-linked list.

class Solution:
    def addTwoNumbers(self, l1, l2):
        ans = ListNode(0)

        temp_ans = ans
        temp_l1 = l1
        temp_l2 = l2
        while temp_l1 or temp_l2:
            temp_ans.val = temp_ans.val + self._add_nodes(temp_l1, temp_l2)

            if temp_ans.val < 10:
                if temp_l1 and temp_l1.next or temp_l2 and temp_l2.next:
                    temp_ans.next = ListNode(0)
            else:
                temp_ans.next = ListNode(1)
                temp_ans.val -= 10

            if temp_l1:
                temp_l1 = temp_l1.next
            if temp_l2:
                temp_l2 = temp_l2.next
            temp_ans = temp_ans.next

        return ans

    def _add_nodes(self, node1, node2):
        # if not node1 and not node2:
            # raise Exception("Two nodes are None")
        try:
            if not node1:
                return node2.val
            if not node2:
                return node1.val
        except:
            print("Two nodes are None.")
            return 0
        if node1 and node2:
            return node1.val + node2.val
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值