-
Notifications
You must be signed in to change notification settings - Fork 0
/
2.两数相加.ts
67 lines (65 loc) · 1.37 KB
/
2.两数相加.ts
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
/*
* @lc app=leetcode.cn id=2 lang=typescript
*
* [2] 两数相加
*/
// @lc code=start
/**
* 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 add = 0
const sum = new ListNode()
let cur = sum
cur.next = null
while (l1 && l2) {
const t = (l1.val + l2.val + add) % 10
add = Math.floor((l1.val + l2.val + add) / 10)
l1 = l1.next
l2 = l2.next
const node = new ListNode()
node.val = t
node.next = null
cur.next = node
cur = cur.next
}
while (l1) {
const t = (l1.val + add) % 10
add = Math.floor((l1.val + add) / 10)
const node = new ListNode()
node.val = t
node.next = null
cur.next = node
cur = cur.next
l1 = l1.next
}
while (l2) {
const t = (l2.val + add) % 10
add = Math.floor((l2.val + add) / 10)
const node = new ListNode()
node.val = t
node.next = null
cur.next = node
cur = cur.next
l2 = l2.next
}
if (add) {
const node = new ListNode()
node.val = 1
node.next = null
cur.next = node
}
return sum.next
}
// @lc code=end