1290. Convert Binary Number in a Linked List to Integer #1926
-
Topics: Given Return the decimal value of the number in the linked list. The most significant bit is at the head of the linked list. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to convert a binary number represented as a singly-linked list into its decimal equivalent. Each node in the linked list contains a bit (0 or 1), with the head node being the most significant bit. The solution involves traversing the linked list and efficiently computing the decimal value using bit manipulation. Approach
Let's implement this solution in PHP: 1290. Convert Binary Number in a Linked List to Integer <?php
// Definition for a singly-linked list node
class ListNode {
public $val = 0;
public $next = null;
public function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
/**
* Main function to convert binary linked list to integer
*
* @param ListNode $head
* @return Integer
*/
function getDecimalValue($head) {
$num = 0;
$current = $head;
while ($current !== null) {
$num = ($num << 1) | $current->val;
$current = $current->next;
}
return $num;
}
// ---------- Example Usage ----------
/**
* Helper function to create linked list from array
*
* @param $arr
* @return mixed|null
*/
function createLinkedList($arr) {
$dummy = new ListNode(0);
$current = $dummy;
foreach ($arr as $val) {
$current->next = new ListNode($val);
$current = $current->next;
}
return $dummy->next;
}
// Example 1
$head = createLinkedList([1, 0, 1]);
echo getDecimalValue($head); // Output: 5
// Example 2
$head = createLinkedList([0]);
echo getDecimalValue($head); // Output: 0
?> Explanation:
This approach efficiently computes the decimal value in linear time with constant space, leveraging bit manipulation for optimal performance. |
Beta Was this translation helpful? Give feedback.
We need to convert a binary number represented as a singly-linked list into its decimal equivalent. Each node in the linked list contains a bit (0 or 1), with the head node being the most significant bit. The solution involves traversing the linked list and efficiently computing the decimal value using bit manipulation.
Approach