leetcode系列(双语)002——GO两数相加

news/2024/6/18 19:16:46 标签: 1024程序员节, leetcode

文章目录

  • 两数相加 | Add Two Numbers
  • 示例
  • 个人解答
  • 官方解答
  • 扩展
    • Algorithm

两数相加 | Add Two Numbers

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 contains a single digit.

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

Add the two numbers and return the sum as a linked list.

请你将两个数相加,并以相同形式返回一个表示和的链表。

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

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

示例

输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.

个人解答

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    return calc(l1 , l2 , 0)
}

func calc(l1 *ListNode, l2 *ListNode, isPlusOne int) *ListNode{
    if l1 == nil && l2 == nil && isPlusOne == 0 {
        return nil
    }
    l1Val := 0
    l2Val := 0
    if l1 != nil {
        l1Val = l1.Val
        l1 = l1.Next
    }
    if l2 != nil {
        l2Val = l2.Val
        l2 = l2.Next
    }
    r := &ListNode{Val : (l1Val + l2Val + isPlusOne)}
    if 9 < r.Val {
        r.Val = r.Val % 10
        isPlusOne = 1
    }else{
        isPlusOne = 0
    }
    r.Next = calc(l1 , l2 , isPlusOne)
    return r

}

官方解答

func addTwoNumbers(l1, l2 *ListNode) (head *ListNode) {
    var tail *ListNode
    carry := 0
    for l1 != nil || l2 != nil {
        n1, n2 := 0, 0
        if l1 != nil {
            n1 = l1.Val
            l1 = l1.Next
        }
        if l2 != nil {
            n2 = l2.Val
            l2 = l2.Next
        }
        sum := n1 + n2 + carry
        sum, carry = sum%10, sum/10
        if head == nil {
            head = &ListNode{Val: sum}
            tail = head
        } else {
            tail.Next = &ListNode{Val: sum}
            tail = tail.Next
        }
    }
    if carry > 0 {
        tail.Next = &ListNode{Val: carry}
    }
    return
}

扩展

Algorithm

Create a new LinkedList, and then push the input two linked lists from the beginning to the back, add every two, and add a new node to the back of the new linked list.

In order to prevent the two input linked lists from being empty at the same time, we create a dummy node, and add the new nodes generated by the addition of the two nodes to the dummy node in order.

Since the dummy node itself cannot be changed, a pointer is used cur to point to the last node of the new linked list. Ok, you can start to add the two linked lists.

This problem is good because the lowest bit is at the beginning of the linked list, so you can directly add them in order from low to high while traversing the linked list. The condition of the while loop, as long as one of the two linked lists is not an empty row, since the linked list may be empty, when taking the current node value, judge first, if it is empty then value is 0, otherwise take the node value.

Then add the two node values, and add carry. Then update carry, directly sum/10, and then create a new node with sum%10 as the value, connect it to the back of cur, and then move cur to the next node.

Then update the two nodes, if they exist, point to the next location. After the while loop exits, the highest carry issue needs to be dealt with specially. If carry is 1, then another node with value 1 is created.

 func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    dummy := &ListNode{}
    carry := 0
    cur := dummy
    for l1 != nil || l2 != nil || carry != 0 {
        s := carry
        if l1 != nil {
            s += l1.Val
        }
        if l2 != nil {
            s += l2.Val
        }
        carry = s / 10
        cur.Next = &ListNode{s % 10, nil}
        cur = cur.Next
        if l1 != nil {
            l1 = l1.Next
        }
        if l2 != nil {
            l2 = l2.Next
        }
    }
    return dummy.Next
}

英语文章出处


http://www.niftyadmin.cn/n/5119805.html

相关文章

Elasticsearch之mapping

文章目录 以显式的方式创建一个映射查看某个具体索引的mapping定义向已存在的映射中添加一个新的属性查看映射中指定字段的定义信息更新已存在映射的某个字段 1、 官方文档地址 2、 字段类型 1、定义&#xff1a;映射是定义文档及其包含的字段如何存储和索引的过程。 2、每个…

【24种设计模式】工厂模式(Factory Pattern)

工厂模式是一种创建型设计模式&#xff0c;它提供了一种创建对象的方式&#xff0c;而无需暴露对象创建的逻辑。在这篇博客中&#xff0c;我们将介绍工厂模式的概念、使用场景以及示例代码。 概念 工厂模式是一种创建型设计模式&#xff0c;它提供了一种创建对象的方式&#…

ESP32网络开发实例-将 ESP32 连接到 EMQX Cloud MQTT Broker

将 ESP32 连接到 EMQX Cloud MQTT Broker 文章目录 将 ESP32 连接到 EMQX Cloud MQTT Broker1、MQTT介绍2、软件准备3、硬件准备4、代码实现5、MQTT测试在本文中,将介绍使用 EMQX Cloud MQTT 服务器。 首先,我们将介绍如何将 ESP32 开发板连接到 EMQX Cloud MQTT 服务器。 我…

Linux PAGE_ALIGN 宏定义的理解

前言 最近再阅读 Linux ion&#xff08;一种内存分配管理&#xff09;时&#xff0c;遇到了 PAGE_ALIGN 宏&#xff0c;这个宏到底是怎么工作的&#xff1f; 【页对齐】时什么意思&#xff1f; 页大小就是 4096 吗&#xff1f; 追踪 PAGE_ALIGN 通过一步一步的追踪&#xff0…

管理类联考——英语二——翻译篇——翻译习惯和技巧

1、翻译习惯 英译汉就是用汉语把英语所表达的内容准确而完整地重新表达出来的过程。翻译过程中需要注意两点&#xff1a; ①翻译需要表达的是句子或文章的内容&#xff0c;而不是结构。 ②英译汉不是简单地将两种语言的结构进行转换&#xff0c;而是分为阅读理解&#xff0c;汉…

Pytorch--3.使用CNN和LSTM对数据进行预测

这个系列前面的文章我们学会了使用全连接层来做简单的回归任务&#xff0c;但是在现实情况里&#xff0c;我们不仅需要做回归&#xff0c;可能还需要做预测工作。同时&#xff0c;我们的数据可能在时空上有着联系&#xff0c;但是简单的全连接层并不能满足我们的需求&#xff0…

AIGC实战——深度学习 (Deep Learning, DL)

AIGC实战——深度学习 0. 前言1. 深度学习基本概念1.1 基本定义1.2 非结构化数据 2. 深度神经网络2.1 神经网络2.2 学习高级特征 3. TensorFlow 和 Keras4. 多层感知器 (MLP)4.1 准备数据4.2 构建模型4.3 检查模型4.4 编译模型4.5 训练模型4.6 评估模型 小结系列链接 0. 前言 …

创建 Edge 浏览器扩展教程(下)

创建 Edge 浏览器扩展教程&#xff08;下&#xff09; 创建扩展教程&#xff0c;第 2 部分1&#xff1a;更新弹出窗口.html以包含按钮2&#xff1a;更新弹出窗口.html在浏览器选项卡顶部显示图像3&#xff1a;创建弹出式 JavaScript 以发送消息4&#xff1a;从任何浏览器选项卡…