forked from NKaty/Algorithms-and-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert-binary-number-in-a-linked-list-to-integer.js
More file actions
50 lines (39 loc) · 1.28 KB
/
convert-binary-number-in-a-linked-list-to-integer.js
File metadata and controls
50 lines (39 loc) · 1.28 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
// Given head which is a reference node to a singly-linked list.
// The value of each node in the linked list is either 0 or 1.
// The linked list holds the binary representation of a number.
// Return the decimal value of the number in the linked list.
// Constraints:
// The Linked List is not empty.
// Number of nodes will not exceed 30.
// Each node's value is either 0 or 1.
function ListNode(val, next) {
this.val = (val === undefined ? 0 : val);
this.next = (next === undefined ? null : next);
}
const getList = (arr) => {
if (!arr.length) throw new Error('Array is empty.');
const head = new ListNode(arr[0]);
let prevNode = head;
for (let i = 1; i < arr.length; i++) {
prevNode.next = new ListNode(arr[i]);
prevNode = prevNode.next;
}
return head;
};
const getDecimalValue = (head) => {
if (!head) return;
let num = 0;
let current = head;
while (current) {
// We start from the most significant bit
// So we must shift our number by one every time
num <<= 1;
// Add current value
// as an option: num |= current.val
num += current.val;
current = current.next;
}
return num;
};
console.log(getDecimalValue(getList([1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0]))); // 18880
console.log(getDecimalValue(getList([0, 0]))); // 0