This approach involves traversing the linked list and building the decimal value using bit manipulation. As the linked list is traversed, the current result is shifted left by one bit (equivalent to multiplying by 2), and the current node's value is added using the OR operation.
Time Complexity: O(n), where n is the number of nodes in the linked list.
Space Complexity: O(1), as we only use a constant amount of additional space.
1function ListNode(val, next) {
2 this.val = (val===undefined ? 0 : val)
3 this.next = (next===undefined ? null : next)
4}
5
6var getDecimalValue = function(head) {
7 let result = 0;
8 while (head !== null) {
9 result = (result << 1) | head.val;
10 head = head.next;
11 }
12 return result;
13};
The JavaScript function getDecimalValue
follows the same logic, updating the result using bitwise manipulation as it traverses through each node.
This approach involves traversing the linked list twice. First, to count the nodes (and hence determine the power of two to start with) and second to compute the decimal value by iterating through the list again, multiplying each binary digit by the appropriate power of two.
Time Complexity: O(n), where n is the number of nodes, but involves two passes.
Space Complexity: O(1), since it uses constant space plus a few variables.
1function ListNode(val, next) {
2 this.val = (val===undefined ? 0 : val);
3 this.next = (next===undefined ? null : next);
4}
5
6var getDecimalValue = function(head) {
7 let length = 0;
8 let current = head;
9 while (current !== null) {
10 length++;
11 current = current.next;
12 }
13 let result = 0;
14 current = head;
15 while (current !== null) {
16 result += current.val * Math.pow(2, --length);
17 current = current.next;
18 }
19 return result;
20};
For JavaScript, two iterations over the list efficiently count the nodes and calculate the decimal value by exploiting duality in powers of two over node positions.