-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.两数相加.js
More file actions
83 lines (77 loc) · 1.77 KB
/
2.两数相加.js
File metadata and controls
83 lines (77 loc) · 1.77 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
//
// 请你将两个数相加,并以相同形式返回一个表示和的链表。
//
// 你可以假设除了数字 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
// 题目数据保证列表表示的数字不含前导零
//
// Related Topics 递归 链表 数学 👍 7639 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let fill = 0
let head = tail = new ListNode(0, null)
while (l1 || l2) {
const l1Value = l1 ? l1.val : 0
const l2Value = l2 ? l2.val : 0
let currentValue = l1Value + l2Value + fill
if(currentValue >= 10) {
currentValue = currentValue % 10
fill = 1
}else {
fill = 0
}
tail.next = new ListNode(currentValue, null)
if(l1) l1 = l1.next
if(l2) l2 = l2.next
tail = tail.next
}
if(fill === 1) {
tail.next = new ListNode(1, null)
}
return head.next
};
//leetcode submit region end(Prohibit modification and deletion)