Convert Binary Number in a Linked List to Integer in JavaScript
This one is an easy problem. Before jumping into the code, you must know what a binary number is and how we convert binary to decimal.
In short, we write any binary number using two digits, 0 and 1.
Example: 101101. To know more about it, check here.
The mathematical formula to convert any binary number to decimal is as shown in the image below:
Since binary numbers are expressed in base-2 numeral systems. Thus, we’ll achieve a decimal by multiplying each binary digit with the 2 raised to the power of the digit’s position. The sum of all these values will give us the decimal number.
This binary number is stored in a singly Linked List, with head
as the starting reference node. For each node, the value will be either 0 or 1 (i.e., the linked list stores the representation of a binary number).
Each node instance will have a value
and a pointer next
which will point to the next node.
Example:
Implementation using JavaScript: