让我们一起啃算法----两数相加

两数相加(Add-Two-Numbers)

这是 LeetCode 的第二题,题目挺常规的,题干如下:

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
    输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出:7 -> 0 -> 8
    原因:342 + 465 = 807
来源:力扣

解题思路

这个题目的解法类似我们小时候算两个多位数的加法:从低位开始相加,大于等于10时则取值的个位数,并向前进1

只不过现在多位数用链表来表示了并且最后的值用链表返回了而已。

根据上面这个思路需要注意的是进位( carry ),相加的时要加上 carry 的值。

实现流程

假设我们有两条链表L1L2,并且初始化了carry为0value为0Point、Head指向一个初始结果链表,其中carry表示低位的进位,value表示结果链表尾节点的值,Ponit指向尾节点用于添加节点存放value的值,Head始终指向结果链表的头节点。
代码实现思路我画成了流程:从上到下,从左到右,配合代码一起看效果更佳哟

具体的代码实现

GO实现

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    var (
        carry        int  // 进位
        currentValue int  // 要追加节点的Val的,也就是图中的value
        centerValue  int  // 中间值
        point        = &ListNode{}
        head         = point
    )
    for l1 != nil && l2 != nil {
        centerValue = l1.Val + l2.Val + carry
        currentValue = centerValue % 10
        carry = centerValue / 10
        // 新增一个节点,用于存储结果
        point.Next = &ListNode{Val: currentValue}
        // point始终指向最后一个节点
        point = point.Next
        l1 = l1.Next
        l2 = l2.Next
    }

    // 上一个for循环执行完毕,有可能l1或者l2仍有节点,下面两个循环就是处理这种情况的

    // 处理两个链表长度不一致的情况
    for l1 != nil {
        centerValue = l1.Val + carry
        currentValue = centerValue % 10
        carry = centerValue / 10
        point.Next = &ListNode{Val: currentValue}
        point = point.Next
        l1 = l1.Next
    }

    // 处理两个链表长度不一致的情况
    for l2 != nil {
        centerValue = l2.Val + carry
        currentValue = centerValue % 10
        carry = centerValue / 10
        point.Next = &ListNode{Val: currentValue}
        point = point.Next
        l2 = l2.Next
    }

    // 如果进位不为0,需再追加一个节点
    if carry == 1 {
        point.Next = &ListNode{Val: 1}
    }

    // 因为head指向的是初始节点,所以head.Next才是我们要的结果链表真正的头节点
    return head.Next
}

其实仔细看上面的代码会发现有很多重复的逻辑,所以简单做了一个优化,代码如下:

func addTwoNumbersOptimize(l1 *ListNode, l2 *ListNode) *ListNode {
    var (
        carry        int
        currentValue int
        centerValue  int
        point        = &ListNode{}
        head         = point
    )
    for l1 != nil || l2 != nil || carry != 0 {
        lValue := 0
        rValue := 0
        if l1 != nil {
            lValue = l1.Val
            l1 = l1.Next
        }
        if l2 != nil {
            rValue = l2.Val
            l2 = l2.Next
        }
        centerValue = lValue + rValue + carry
        currentValue = centerValue % 10
        carry = centerValue / 10
        point.Next = &ListNode{Val: currentValue}
        point = point.Next

    }
    return head.Next
}

总结

每天进步一点点,加油!
算法教程项目,每天更新一题,点个 star 支持一下呀
https://github.com/wx-satellite/learning-a...

本作品采用《CC 协议》,转载必须注明作者和本文链接
三斤
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 2

老哥,这个系列蛮好的,但是图片如果是透明的字体颜色就要调整一下,不然在论坛的深色模式下一个字都看不到 : )

3年前 评论
三斤和他的喵 (楼主) 3年前
三斤和他的喵 (楼主) 3年前
function addTwoNumbers($first, $second)
{
    $carry = 0;
    $str = '';

    // 循环次数以较长的数组为准
    $firstCount = count($first);
    $secondCount = count($second);
    $count = $firstCount > $secondCount ? $firstCount : $secondCount;

    for ($i = 0; $i < $count; $i++) {
        $firstValue = $first[0] ?? 0;
        $secondValue = $second[0] ?? 0;
        array_shift($first);
        array_shift($second);

        // 计算,额外处理最后一次的情况,在空字符串前追加数据
        $centerValue = $firstValue + $secondValue + $carry;
        $currentValue = $i === $count - 1 ? (int)$centerValue : $centerValue % 10;
        $carry = $centerValue / 10;
        $str = $currentValue . $str;
    }

    return $str;
}

echo addTwoNumbers([2, 4, 3], [5, 6, 4]); // output: 807
echo addTwoNumbers([2, 4, 3], [5, 6, 7]); // output: 1107

继续模仿楼主的代码,用PHP实现了一下,楼主的代码需要判断一下,如果是最后一次循环,currentValue >= 10 的时候,需要使用 int 之后的值了,不需要 % 10

3年前 评论
三斤和他的喵 (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!