Skip to content

Commit 8e8ba4c

Browse files
committed
Add binary to decimal conversion from linkedlist
1 parent 83f0aa7 commit 8e8ba4c

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
class Node {
2+
constructor(value) {
3+
this.value = value;
4+
this.next = null;
5+
}
6+
}
7+
8+
class LinkedList {
9+
constructor(value) {
10+
this.head = null;
11+
this.tail = null;
12+
this.length = 0;
13+
}
14+
15+
push(value) {
16+
const newNode = new Node(value);
17+
if(!this.head) {
18+
this.head = newNode;
19+
this.tail = newNode;
20+
} else {
21+
this.tail.next = newNode;
22+
this.tail = newNode;
23+
}
24+
this.length++;
25+
return this;
26+
}
27+
28+
findMiddleNodeWithLength() {
29+
let temp = this.head;
30+
for(let i = 0; i < Math.floor(this.length/2); i++) {
31+
temp = temp.next;
32+
}
33+
return temp;
34+
}
35+
36+
binaryToDecimal() {
37+
let current = this.head;
38+
let decimal = 0;
39+
for (let i = this.length -1; i >=0; i--) {
40+
decimal += Math.pow(2, i) * current.value;
41+
current = current.next;
42+
}
43+
return decimal;
44+
}
45+
46+
binaryToDecimalDoublingMethod() {
47+
let current = this.head;
48+
let decimal = 0;
49+
while(current !== null) {
50+
decimal = decimal * 2 + current.value;
51+
current = current.next;
52+
}
53+
return decimal;
54+
}
55+
}
56+
57+
const myLinkedList = new LinkedList();
58+
myLinkedList.push(1);
59+
myLinkedList.push(0);
60+
myLinkedList.push(0);
61+
myLinkedList.push(1);
62+
63+
myLinkedList.binaryToDecimalDoublingMethod();
64+
65+
const myLinkedList1 = new LinkedList();
66+
myLinkedList1.push(1);
67+
myLinkedList1.push(0);
68+
myLinkedList1.push(1);
69+
myLinkedList1.push(1);
70+
71+
myLinkedList1.binaryToDecimal();
72+

0 commit comments

Comments
 (0)