LeetCode系列:2 Add Two Numbers

本文介绍了一种使用链表实现加法的方法,通过遍历两个逆序存储的链表,逐位相加并处理进位,最终返回一个新的链表作为两数之和。

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

Q:You are given two non-empty linked lists representing two nonnegative 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.


Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

E:给定两个非空链表代表两个非负整数,这两个数字被逆序存储并且他们的每一个节点只存一个单一数字,返回这两个数字加起来组合成的新链表。

你可以假设这两个数字不是0开头,除了0它自己

e.g.
输入:
链表1(2 -> 4 -> 3) 链表2(5 -> 6 -> 4)
因为342 + 465=807,所以
输出:
新链表:
7 -> 0 -> 8

A:
Approach:

因为链表存储顺序刚好和我们做加法的顺序一致,所以我们只需要按照正常数学加法来操作这两个数字即可。
每次拿链表1和链表2的一个元素相加,这个时候可能会有几种情况:
a、链表1和链表2长度不相等,此时取值一个能取,一个已经没有了;
b、链表1和链表2相加,有进位;
c、链表其中一个没有元素,一个还有元素且此时还有进位,需要元素与进位相加;
d、都没有元素,但是此时还有进位。

class Solution {
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        
        let header = ListNode(0) 
        var list1 = l1, list2 = l2, carry = 0, tempNode = header
        while list1 != nil || list2 != nil || carry != 0 {//考虑上面提到的a,b,c,d四种情况
            if list1 != nil {
                carry += list1!.val
                list1 = list1?.next
            }
            if list2 != nil {
                carry += list2!.val
                list2 = list2?.next
            }
            tempNode.next = ListNode(carry%10)
            tempNode = tempNode.next!
            carry /= 10	//获取进位,如果没有,则为0

        }
        return header.next//因为一开始实例化的是ListNode(0) ,所以要从下一个开始,不然会多一个0元素
    }
}
Complexity Analysis:
  • 时间复杂度: O(n)。(LeetCode:64 ms)
  • 空间复杂度:O(n)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值