Go 和 PHP 基于两组数计算相加的结果

栏目: IT技术 · 发布时间: 6年前

内容简介:原文链接:这是给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

原文链接: go letcode ,作者:三斤和他的喵 php 代码个人原创

两数相加(Add-Two-Numbers)

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

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)

输出:7 -> 0 -> 8

原因:342 + 465 = 807

来源:力扣

解题思路

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

Go 和 PHP 基于两组数计算相加的结果

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

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

Go 实现:

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
}

PHP 实现:

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

带货 -> 去看

首发于 何晓东 博客

欢迎关注我们的微信公众号,每天学习 Go 知识

Go 和 PHP 基于两组数计算相加的结果

以上所述就是小编给大家介绍的《Go 和 PHP 基于两组数计算相加的结果》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Seasoned Schemer

The Seasoned Schemer

Daniel P. Friedman、Matthias Felleisen / The MIT Press / 1995-12-21 / USD 38.00

drawings by Duane Bibbyforeword and afterword by Guy L. Steele Jr.The notion that "thinking about computing is one of the most exciting things the human mind can do" sets both The Little Schemer (form......一起来看看 《The Seasoned Schemer》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具