-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
46 lines (41 loc) · 1 KB
/
solution.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
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 plusOne (head: ListNode | null): ListNode | null {
if (!head) {
return null;
}
return reverse(add1(reverse(head)));
}
function reverse (head:ListNode):ListNode {
const dummyHead = new ListNode();
while (head) {
const next = head.next;
head.next = dummyHead.next;
dummyHead.next = head;
head = next;
}
return dummyHead.next;
}
function add1 (head:ListNode) {
let node = head;
let addon = 1;
let prev = head;
while (node && addon) {
const sum = addon + node.val;
const digit = sum % 10;
node.val = digit;
addon = (sum - digit) / 10;
prev = node;
node = node.next;
}
if (addon) {
prev.next = new ListNode(addon);
}
return head;
}