力扣00002.两数相加


题目描述

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

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

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

示例 1:

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

示例 2:

输入:l1 = [0], l2 = [0]
输出:[0]

示例 3:

输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]

提示:

  • 每个链表中的节点数在范围 [1, 100] 内
  • 0 <= Node.val <= 9
  • 题目数据保证列表表示的数字不含前导零

解决方法

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode(0);
ListNode* current = dummy;
int carry = 0;
while (l1 || l2 || carry) {
int val1 = (l1 != nullptr) ? l1->val : 0;
int val2 = (l2 != nullptr) ? l2->val : 0;
int sum = val1 + val2 + carry;
carry = sum / 10;
current->next = new ListNode(sum % 10);
current = current->next;
if (l1) l1 = l1->next;
if (l2) l2 = l2->next;
}
return dummy->next;
}
};

结果

执行用时 : 24 ms, 击败 71.16% 使用 C++ 的用户

内存消耗 : 70.01 MB, 击败 74.88% 使用 C++ 的用户


Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry > 0) {
int val1 = (l1 != null) ? l1.val : 0;
int val2 = (l2 != null) ? l2.val : 0;
int sum = val1 + val2 + carry;
carry = sum / 10;
current.next = new ListNode(sum % 10);
current = current.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
return dummy.next;
}
}

结果

执行用时 : 1 ms, 击败 100.00% 使用 Java 的用户

内存消耗 : 42.10 MB, 击败 49.96% 使用 Java 的用户


Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
current = dummy
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
total = val1 + val2 + carry
carry = total // 10
current.next = ListNode(total % 10)
current = current.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
return dummy.next

结果

执行用时 : 40 ms, 击败 91.45% 使用 Python 的用户

内存消耗 : 12.86 MB, 击败 97.89% 使用 Python 的用户


Python3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0)
current = dummy
carry = 0
while l1 or l2 or carry:
val1 = l1.val if l1 else 0
val2 = l2.val if l2 else 0
total = val1 + val2 + carry
carry = total // 10
current.next = ListNode(total % 10)
current = current.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
return dummy.next

结果

执行用时 : 68 ms, 击败 38.97% 使用 Python3 的用户

内存消耗 : 16.16 MB, 击败 17.37% 使用 Python3 的用户


C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* current = dummy;
int carry = 0;
while (l1 != NULL || l2 != NULL || carry != 0) {
int val1 = (l1 != NULL) ? l1->val : 0;
int val2 = (l2 != NULL) ? l2->val : 0;
int sum = val1 + val2 + carry;
carry = sum / 10;
current->next = (struct ListNode*)malloc(sizeof(struct ListNode));
current = current->next;
current->val = sum % 10;
current->next = NULL;
if (l1 != NULL) l1 = l1->next;
if (l2 != NULL) l2 = l2->next;
}
struct ListNode* result = dummy->next;
free(dummy);
return result;
}

结果

执行用时 : 20 ms, 击败 14.59% 使用 C 的用户

内存消耗 : 8.39 MB, 击败 27.32% 使用 C 的用户


C#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int val1 = (l1 != null) ? l1.val : 0;
int val2 = (l2 != null) ? l2.val : 0;
int sum = val1 + val2 + carry;
carry = sum / 10;
current.next = new ListNode(sum % 10);
current = current.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
return dummy.next;
}
}

结果

执行用时 : 72 ms, 击败 99.82% 使用 C# 的用户

内存消耗 : 50.63 MB, 击败 5.13% 使用 C# 的用户


JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/

var addTwoNumbers = function(l1, l2) {
let dummy = new ListNode(0);
let current = dummy;
let carry = 0;
while (l1 !== null || l2 !== null || carry !== 0) {
let val1 = (l1 !== null) ? l1.val : 0;
let val2 = (l2 !== null) ? l2.val : 0;
let sum = val1 + val2 + carry;
carry = Math.floor(sum / 10);
current.next = new ListNode(sum % 10);
current = current.next;
if (l1 !== null) l1 = l1.next;
if (l2 !== null) l2 = l2.next;
}
return dummy.next;
};

结果

执行用时 : 92 ms, 击败 81.79% 使用 JavaScript 的用户

内存消耗 : 45.96 MB, 击败 55.34% 使用 JavaScript 的用户


TypeScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/

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

结果

执行用时 : 124 ms, 击败 15.47% 使用 TypeScript 的用户

内存消耗 : 56.84 MB, 击败 5.07% 使用 TypeScript 的用户


PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
class Solution {

/**
* @param ListNode $l1
* @param ListNode $l2
* @return ListNode
*/
function addTwoNumbers($l1, $l2) {
$dummy = new ListNode(0);
$current = $dummy;
$carry = 0;
while ($l1 !== null || $l2 !== null || $carry !== 0) {
$val1 = ($l1 !== null) ? $l1->val : 0;
$val2 = ($l2 !== null) ? $l2->val : 0;
$sum = $val1 + $val2 + $carry;
$carry = intval($sum / 10);
$current->next = new ListNode($sum % 10);
$current = $current->next;
if ($l1 !== null) $l1 = $l1->next;
if ($l2 !== null) $l2 = $l2->next;
}
return $dummy->next;
}
}

结果

执行用时 : 12 ms, 击败 87.39% 使用 PHP 的用户

内存消耗 : 18.92 MB, 击败 76.12% 使用 PHP 的用户


Swift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
let dummy = ListNode(0)
var current: ListNode? = dummy
var carry = 0
var l1 = l1
var l2 = l2
while l1 != nil || l2 != nil || carry != 0 {
let val1 = l1?.val ?? 0
let val2 = l2?.val ?? 0
let sum = val1 + val2 + carry
carry = sum / 10
current?.next = ListNode(sum % 10)
current = current?.next
l1 = l1?.next
l2 = l2?.next
}
return dummy.next
}
}

结果

执行用时 : 36 ms, 击败 65.63% 使用 Swift 的用户

内存消耗 : 13.84 MB, 击败 50.15% 使用 Swift 的用户


Kotlin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
val dummy = ListNode(0)
var current: ListNode? = dummy
var carry = 0
var p1 = l1
var p2 = l2
while (p1 != null || p2 != null || carry != 0) {
val val1 = p1?.`val` ?: 0
val val2 = p2?.`val` ?: 0
val sum = val1 + val2 + carry
carry = sum / 10
current?.next = ListNode(sum % 10)
current = current?.next
p1 = p1?.next
p2 = p2?.next
}
return dummy.next
}
}

结果

执行用时 : 224 ms, 击败 29.05% 使用 Kotlin 的用户

内存消耗 : 43.02 MB, 击败 41.21% 使用 Kotlin 的用户


Dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode? next;
* ListNode([this.val = 0, this.next]);
* }
*/
class Solution {
ListNode? addTwoNumbers(ListNode? l1, ListNode? l2) {
ListNode dummy = ListNode(0);
ListNode? current = dummy;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int val1 = l1?.val ?? 0;
int val2 = l2?.val ?? 0;
int sum = val1 + val2 + carry;
carry = sum ~/ 10;
current!.next = ListNode(sum % 10);
current = current.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
return dummy.next;
}
}

结果

执行用时 : 312 ms, 击败 100.00% 使用 Dart 的用户

内存消耗 : 160.98 MB, 击败 85.71% 使用 Dart 的用户


Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
dummy := &ListNode{} // 创建一个哑节点
current := dummy
carry := 0
for l1 != nil || l2 != nil || carry != 0 {
val1, val2 := 0, 0
if l1 != nil {
val1 = l1.Val
l1 = l1.Next
}
if l2 != nil {
val2 = l2.Val
l2 = l2.Next
}
sum := val1 + val2 + carry
carry = sum / 10
current.Next = &ListNode{Val: sum % 10}
current = current.Next
}
return dummy.Next
}

结果

执行用时 : 12 ms, 击败 31.30% 使用 Go 的用户

内存消耗 : 4.15 MB, 击败 90.24% 使用 Go 的用户


Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val = 0, _next = nil)
# @val = val
# @next = _next
# end
# end
# @param {ListNode} l1
# @param {ListNode} l2
# @return {ListNode}
def add_two_numbers(l1, l2)
dummy = ListNode.new(0)
current = dummy
carry = 0
while l1 || l2 || carry != 0
val1 = l1 ? l1.val : 0
val2 = l2 ? l2.val : 0
sum = val1 + val2 + carry
carry = sum / 10
current.next = ListNode.new(sum % 10)
current = current.next
l1 = l1.next if l1
l2 = l2.next if l2
end
dummy.next
end

结果

执行用时 : 100 ms, 击败 40.00% 使用 Ruby 的用户

内存消耗 : 206.91 MB, 击败 8.00% 使用 Ruby 的用户


Scala

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
var dummy = new ListNode()
var current = dummy
var carry = 0
var p1 = l1
var p2 = l2
while (p1 != null || p2 != null || carry != 0) {
val x = if (p1 != null) p1.x else 0
val y = if (p2 != null) p2.x else 0
val sum = x + y + carry
carry = sum / 10
current.next = new ListNode(sum % 10)
current = current.next
if (p1 != null) p1 = p1.next
if (p2 != null) p2 = p2.next
}
dummy.next
}
}

结果

执行用时 : 588 ms, 击败 53.33% 使用 Scala 的用户

内存消耗 : 57.63 MB, 击败 66.67% 使用 Scala 的用户


Rust

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
Self::add_two(&l1, &l2, 0)
}
fn add_two(l1: &Option<Box<ListNode>>, l2: &Option<Box<ListNode>>, carry: i32) -> Option<Box<ListNode>> {
match (l1, l2) {
(None, None) => {
if carry == 0 {
return None;
}
Some(Box::new(ListNode::new(carry)))
}
(None, Some(n2)) => Self::add_two(l2, l1, carry),
(Some(n1), None) => {
let mut l1 = n1.clone();
let sum = carry + l1.val;
l1.val = sum % 10;
l1.next = Self::add_two(&n1.next, &None, sum / 10);
Some(l1)
}
(Some(n1), Some(n2)) => {
let mut l1 = n1.clone();
let mut l2 = n2.clone();
let sum = carry + l1.val + l2.val;
l1.val = sum % 10;
l1.next = Self::add_two(&l1.next, &l2.next, sum / 10);
Some(l1)
}
}
}
}

结果

执行用时 : 12 ms, 击败 2.21% 使用 Rust 的用户

内存消耗 : 2.15 MB, 击败 42.59% 使用 Rust 的用户


Racket

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
; Definition for singly-linked list:
#|

; val : integer?
; next : (or/c list-node? #f)
(struct list-node
(val next) #:mutable #:transparent)

; constructor
(define (make-list-node [val 0])
(list-node val #f))

|#

(define (add-two-numbers l1 l2)
(define (calculate-carry x)
(quotient/remainder x 10))
(let loop ([list1 l1] [list2 l2] [remainder 0])
(match* (list1 list2)
[(#f #f) (if (zero? remainder) #f (make-list-node remainder))]
[((list-node val rest) #f)
(define-values (new-remainder result) (calculate-carry (+ val remainder)))
(list-node result (loop rest #f new-remainder))]
[(#f (list-node val rest))
(define-values (new-remainder result) (calculate-carry (+ val remainder)))
(list-node result (loop #f rest new-remainder))]
[((list-node val1 rest1) (list-node val2 rest2))
(define-values (new-remainder result) (calculate-carry (+ val1 val2 remainder)))
(list-node result (loop rest1 rest2 new-remainder))])))

结果

执行用时 : 280 ms, 击败 14.29% 使用 Racket 的用户

内存消耗 : 124.67 MB, 击败 28.57% 使用 Racket 的用户


Erlang

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
%% Definition for singly-linked list.
%%
%% -record(list_node, {val = 0 :: integer(),
%% next = null :: 'null' | #list_node{}}).

-spec add_two_numbers(L1 :: #list_node{} | null, L2 :: #list_node{} | null) -> #list_node{} | null.
add_two_numbers(L1, L2) ->
add_two_numbers(L1, L2, 0).
add_two_numbers(null, null, 0) ->
null;
add_two_numbers(null, L2, Carry) ->
add_carry(L2, Carry);
add_two_numbers(L1, null, Carry) ->
add_carry(L1, Carry);
add_two_numbers(#list_node{val = Val1, next = Next1} = L1, #list_node{val = Val2, next = Next2}, Carry) ->
{Sum, NewCarry} = calculate_carry(Val1 + Val2 + Carry),
#list_node{val = Sum, next = add_two_numbers(Next1, Next2, NewCarry)}.
calculate_carry(Sum) when Sum < 10 ->
{Sum, 0};
calculate_carry(Sum) ->
{Sum rem 10, 1}.
add_carry(null, 0) ->
null;
add_carry(null, Carry) ->
#list_node{val = Carry, next = null};
add_carry(#list_node{val = Val, next = Next}, Carry) ->
{Sum, NewCarry} = calculate_carry(Val + Carry),
#list_node{val = Sum, next = add_carry(Next, NewCarry)}.

结果

执行用时 : 296 ms, 击败 20.00% 使用 Erlang 的用户

内存消耗 : 49.96 MB, 击败 60.00% 使用 Erlang 的用户


Elixir

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Definition for singly-linked list.
#
# defmodule ListNode do
# @type t :: %__MODULE__{
# val: integer,
# next: ListNode.t() | nil
# }
# defstruct val: 0, next: nil
# end

defmodule Solution do
@spec add_two_numbers(ListNode.t() | nil, ListNode.t() | nil) :: ListNode.t() | nil
def add_two_numbers(nil, nil), do: nil
def add_two_numbers(nil, l2), do: l2
def add_two_numbers(l1, nil), do: l1
def add_two_numbers(%ListNode{val: val1, next: next1} = l1, %ListNode{val: val2, next: next2} = l2) do
{sum, carry} = calculate_sum_and_carry(val1 + val2)
new_node = %ListNode{val: sum, next: add_two_numbers(next1, next2)}
adjust_node(new_node, carry)
end
defp calculate_sum_and_carry(sum) when sum < 10, do: {sum, 0}
defp calculate_sum_and_carry(sum), do: {rem(sum, 10), 1}
defp adjust_node(node, 0), do: node
defp adjust_node(node, carry), do: %ListNode{node | next: add_carry(node.next, carry)}
defp add_carry(nil, 0), do: nil
defp add_carry(nil, carry), do: %ListNode{val: carry, next: nil}
defp add_carry(%ListNode{val: val, next: next}, carry) do
{sum, new_carry} = calculate_sum_and_carry(val + carry)
%ListNode{val: sum, next: add_carry(next, new_carry)}
end
end

结果

执行用时 : 364 ms, 击败 100.00% 使用 Elixir 的用户

内存消耗 : 68.29 MB, 击败 -% 使用 Elixir 的用户