We are given a singly linked list, where each node contains a single binary digit (0 or 1). Our goal is to convert this binary number represented by the linked list into an integer.
The linked list format is as follows:
val
attribute, which is either 0 or 1.next
attribute, which points to the next node in the linked list or None
if it is the last node.0
or 1
.Let’s implement the solution using a class definition for the nodes and the function to convert the binary number in a linked list to an integer.
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
# Initialize result
num = 0
current = head
while current is not None:
# Shift the current number to the left (multiply by 2)
# Add the current node's value
num = (num << 1) | current.val
# Move to the next node
current = current.next
return num
num
): This will store the final integer value.num
by 1 (equivalent to multiplying by 2).0
or 1
) to num
using the OR |
operation.num
now contains the decimal value of the binary number represented by the linked list.n
is the number of nodes in the linked list. This is because we traverse each node exactly once.This solution ensures efficient traversal and conversion from binary to decimal, leveraging bit manipulation for optimal performance.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?