【LeetCode】【2】Add Two Numbers

本文最后更新于:2021年12月22日 中午

【主页】系列文章目录

【LeetCode】系列目录


LeetCode系列

Q:You are given two non-empty linked lists representing two nonnegative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

1
2
3
4
5
6
7
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

E:给定两个非空链表代表两个非负整数,这两个数字被逆序存储并且他们的每一个节点只存一个单一数字,返回这两个数字加起来组合成的新链表。

e.g.
1
2
3
4
5
6
7
你可以假设这两个数字不是0开头,除了0它自己
输入:
链表1:(2 -> 4 -> 3) 链表2:(5 -> 6 -> 4)
因为342 + 465=807,所以
输出:
新链表:
7 -> 0 -> 8

A:

Approach:

因为链表存储顺序刚好和我们做加法的顺序一致,所以我们只需要按照正常数学加法来操作这两个数字即可。
每次拿链表1和链表2的一个元素相加,这个时候可能会有几种情况:
a、链表1和链表2长度不相等,此时取值一个能取,一个已经没有了;
b、链表1和链表2相加,有进位;
c、链表其中一个没有元素,一个还有元素且此时还有进位,需要元素与进位相加;
d、都没有元素,但是此时还有进位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {

let header = ListNode(0)
var list1 = l1, list2 = l2, carry = 0, tempNode = header
while list1 != nil || list2 != nil || carry != 0 {//考虑上面提到的a,b,c,d四种情况
if list1 != nil {
carry += list1!.val
list1 = list1?.next
}
if list2 != nil {
carry += list2!.val
list2 = list2?.next
}
tempNode.next = ListNode(carry%10)
tempNode = tempNode.next!
carry /= 10 //获取进位,如果没有,则为0

}
return header.next//因为一开始实例化的是ListNode(0) ,所以要从下一个开始,不然会多一个0元素
}
}
Complexity Analysis:
  • 时间复杂度: O(n)。(LeetCode:64 ms)
  • 空间复杂度:O(n)。

联系方式

邮箱: xiebangyao_1994@163.com

相关账号: