-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddTwoNumber.ts
More file actions
83 lines (66 loc) · 2.22 KB
/
Copy pathaddTwoNumber.ts
File metadata and controls
83 lines (66 loc) · 2.22 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
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 getNumber(linkedList: ListNode | null): string {
let result = linkedList.val.toString();
let nextNodeValue = linkedList.next;
while (nextNodeValue !== null) {
result = nextNodeValue.val.toString() + result;
nextNodeValue = nextNodeValue.next;
}
return result;
}
function plusStringNumber(firstNumber: string, secondNumber: string): string {
let tempPlusValue = 0;
let arrayLength = secondNumber.length;
let resultPlus = '';
// Add temp zero number at the beginning of the number has less digits
let tempZero = Array.from(
{ length: Math.abs(firstNumber.length - secondNumber.length) },
() => '0'
).join('');
if (firstNumber.length < secondNumber.length) {
firstNumber = tempZero + firstNumber;
} else {
secondNumber = tempZero + secondNumber;
arrayLength = firstNumber.length;
}
// Plus from last index digit to first index digit
for (let index = arrayLength - 1; index >= 0; index--) {
let plus = Number(firstNumber[index]) + Number(secondNumber[index]) + tempPlusValue;
tempPlusValue = 0;
if (plus >= 10) {
tempPlusValue = Math.floor(plus / 10);
plus = plus % 10;
}
resultPlus = plus.toString() + resultPlus;
}
// Add 1 at the beginning of result string
if (tempPlusValue > 0) {
resultPlus = '1' + resultPlus;
}
return resultPlus;
}
function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null {
let firstNumber = getNumber(l1);
let secondNumber = getNumber(l2);
const plus = plusStringNumber(firstNumber, secondNumber);
const resultLinkNode = new ListNode();
let node = resultLinkNode;
const digits = plus.split('');
console.log(digits);
for (let index = digits.length - 1; index >= 0; index--) {
node.val = Number(digits[index]);
node.next = index === 0 ? null : new ListNode();
node = node.next;
}
return resultLinkNode;
}
const firstLinkedList = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))));
const secondLinkedList = new ListNode(9, new ListNode(9, new ListNode(9)));
console.log(addTwoNumbers(firstLinkedList, secondLinkedList));