描述

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

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

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

示例

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

输出:7 -> 0 -> 8

原因:342 + 465 = 807

分析

其实和我们算加法一样,从个位开始计算就行了,如图所示



只要把两条链表相应位置相加,记录是否有进位(通过sum/10来判断),有则进位,添加到一条新的链表结点就行了。值得注意的是,相加后有几种情景,分别是

情景 结果
1+1 不进位
12+8 进一次位
9993+7 连续进位
0+12 有空的结点

对应结点的和 sum = x + y + carry,其中carry 则是 sum/10,对应的该位结点值为 sum%10。

因为只需要遍历最长的链表,挨个结点相加,所以时间复杂度为 O(max(m,n)),m 和 n 分别是两条链表的长度;

需要新的一条链表来记录结果,最多为 max(m,n)+1(最高位有进位情况),所以空间复杂度为 O(max(m,n))。

实现

C#

class Solution
{
public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
{
ListNode dummyHead = new ListNode(0);
if (l1 == null && l2 == null)
return dummyHead;
int carry = 0;
ListNode curr = dummyHead;
while (l1 != null || l2 != null)
{
int num1 = l1?.val ?? 0;
int num2 = l2?.val ?? 0;
int sum = num1 + num2 + carry;
curr.next = new ListNode(sum % 10);
curr = curr.next;
carry = sum / 10;
l1 = l1?.next;
l2 = l2?.next;
}
if (carry != 0)
{
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
}

C++

class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode preHead(0), *p = &preHead;
int carry = 0;
while (l1 || l2 || carry) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
carry = sum / 10;
p->next = new ListNode(sum % 10);
p = p->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return preHead.next;
}
};

Python

class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
carry = 0
dummy_head = ListNode(None)
curr = dummy_head
while l1 or l2:
sum = 0;
if l1:
sum += l1.val
l1 = l1.next
if l2:
sum += l2.val
l2 = l2.next
sum += carry
curr.next = ListNode(sum%10)
curr = curr.next
carry = sum//10
if carry != 0:
curr.next = ListNode(carry)
return dummy_head.next

Typescript

function addTwoNumbers(
l1: ListNode | null,
l2: ListNode | null
): ListNode | null {
let dummyHead: ListNode | null = new ListNode();
let carry: number = 0;
let curr: ListNode | null = dummyHead;
while (l1 || l2) {
let sum: number = 0;
if (l1) {
sum += l1.val;
l1 = l1.next;
}
if (l2) {
sum += l2.val;
l2 = l2.next;
}
sum += carry;
curr.next = new ListNode(sum % 10);
curr = curr.next;
carry = Math.floor(sum / 10);
}
if (carry != 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}

Java

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
if (l1 == null && l2 == null)
return head;
int sum = 0, carry = 0;
ListNode curr = head;
while (l1 != null || l2 != null) {
int num1 = l1 == null ? 0 : l1.val;
int num2 = l2 == null ? 0 : l2.val;
sum = num1 + num2 + carry;
curr.next = new ListNode(sum % 10);
curr = curr.next;
carry = sum / 10;
l1 = l1 == null ? l1 : l1.next;
l2 = l2 == null ? l2 : l2.next;
}
if (carry != 0)
curr.next = new ListNode(carry);
return head.next;
}
}

Rust

impl Solution {
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
carried(l1, l2, 0)
}
}
fn carried(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>, mut carry: i32) -> Option<Box<ListNode>> {
if l1.is_none() && l2.is_none() && carry == 0 {
None
} else {
Some(Box::new(ListNode {
next: carried(l1.and_then(|x| {carry += x.val; x.next}),
l2.and_then(|x| {carry += x.val; x.next}),
carry / 10
),
val: carry % 10
}))
}
}

引用

截图来自LeetCode中国.

所有代码均可通过访问Github获取

LeetCode-02 两数相加(Add Two Numbers)的更多相关文章

  1. LeetCode 2. 两数相加(Add Two Numbers)

    2. 两数相加 2. Add Two Numbers 题目描述 You are given two non-empty linked lists representing two non-negati ...

  2. [Swift]LeetCode2. 两数相加 | Add Two Numbers

    You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...

  3. LeetCode 2:两数相加 Add Two Numbers

    ​给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字.如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和 ...

  4. 链表两数相加(add two numbers)

    问题 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它 ...

  5. 2.两数相加(Add Two Numbers) C++

    第一想法是顺着题目的原因,将两链表分别转化为一个数字,再将数字相加,然后把结果转化为字符串,存到答案链表中.但是数据太大会溢出! 所以,要在计算一对数字的过程当中直接存储一个结果,注意结果大于9时进位 ...

  6. LeetCode 445. 两数相加 II(Add Two Numbers II)

    445. 两数相加 II 445. Add Two Numbers II 题目描述 给定两个非空链表来代表两个非负整数.数字最高位位于链表开始位置.它们的每个节点只存储单个数字.将这两数相加会返回一个 ...

  7. Leetcode 002. 两数相加

    1.题目描述 给出两个 非空 的链表用来表示两个非负的整数.其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字. 如果,我们将这两个数相加起来,则会返回一个新的链表 ...

  8. LeetCode 445——两数相加 II

    1. 题目 2. 解答 2.1 方法一 在 LeetCode 206--反转链表 和 LeetCode 2--两数相加 的基础上,先对两个链表进行反转,然后求出和后再进行反转即可. /** * Def ...

  9. LeetCode 2. 两数相加(Add Two Numbers)

    题目描述 给定两个非空链表来表示两个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字.将两数相加返回一个新的链表. 你可以假设除了数字 0 之外,这两个数字都不会以零开头. 示例: 输入: ...

  10. 【LeetCode】两数相加

    题目描述 给出两个非空的链表用来表示两个非负的整数.其中,它们各自的位数是按照逆序的方式存储的,并且它们的每个节点只能存储一位数字. 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和. ...

随机推荐

  1. java中实现File文件的重命名(renameTo)、将文件移动到其他目录下、文件的复制(copy)、目录和文件的组合(更加灵活方便)

    欢迎加入刚建立的社区:http://t.csdn.cn/Q52km 加入社区的好处: 1.专栏更加明确.便于学习 2.覆盖的知识点更多.便于发散学习 3.大家共同学习进步 3.不定时的发现金红包(不多 ...

  2. 测试开发HTTP请求过程(一)

    测试开发HTTP请求过程 HTTP请求过程: 首先要熟悉http请求过程: 1,服务端建立socket监听 2,客户端发送http请求 3,客户端与服务端建立socket连接 4,客户端------t ...

  3. 分享个好东西 - 两行前端代码搞定bilibili链接转视频

    只需要在您的要解析B站视频的页面的</body>前面加上下面两行代码即可,脚本会在客户端浏览器里解析container所匹配到的容器里的B站超链接 (如果不是外围有a标签的超链接只是纯粹的 ...

  4. Python学习三天计划-3

    面向对象 一.类的定义 1.类定义 class是关键字,表示要定义类了 类的属性,即定义在类中的变量(成员变量) 类的行为,即定义在类中的函数(成员方法) 2.对象 创建类对象的语法: class S ...

  5. Pytorch模型量化

    在深度学习中,量化指的是使用更少的bit来存储原本以浮点数存储的tensor,以及使用更少的bit来完成原本以浮点数完成的计算.这么做的好处主要有如下几点: 更少的模型体积,接近4倍的减少: 可以更快 ...

  6. 题解 P4058 [Code+#1]木材

    前言 这什么题啊,不就是个二分答案我从65到100都经历了一遍--(瞬间气哭) \(\sf {Solution}\) 题目理解起来不难的,大意就懒得写了. 一眼二分答案. 此题属于在形如 \(\{0, ...

  7. el-scrollbar 监测滚动条

    export function processScroll (_this) {   let _self = _this   let scrollbarEl = _this.$parent.wrap   ...

  8. 6、将两个字符串连接起来,不使用strcat函数

    /* 将两个字符串连接起来,不使用strcat函数 */ #include <stdio.h> #include <stdlib.h> void strCat(char *pS ...

  9. DHorse系列文章之maven打包

    插件打包 这种方式是平时最常用的,首先要下载并安装maven环境,然后在被打包的项目中引入插件,有各种各样的打包插件,比如springboot自带插件: <plugin> <grou ...

  10. CmakeLists简单使用总结

    单文件工程和多级目录工程CmakeLists.txt编写分享 你若发现该帖中有待商榷的地方,还请指正赐教,先行拜谢了! 1 main.c单文件工程CmakeLists.txt 1.1 目录结构 1.2 ...