Solving Leetcode Interviews in Seconds with AI: Convert Binary Number in a Linked List to Integer
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1290" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. 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: Input: head = [1,0,1] Output: 5 Explanation: (101) in base 2 = (5) in base 10 Example 2: Input: head = [0] Output: 0 Constraints: The Linked List is not empty. Number of nodes will not exceed 30. Each node's value is either 0 or 1.
Explanation
Here's the solution to convert a binary linked list to its decimal representation:
- Approach: Iterate through the linked list, updating the decimal value at each step. For each node, left-shift the current decimal value by one bit (multiply by 2) and add the node's value. This effectively simulates the binary-to-decimal conversion process.
Optimal Solution: Initialize the decimal value to 0. Iterate through the linked list, updating the
decimal_valueasdecimal_value = decimal_value * 2 + node.val.Complexity:
- Runtime: O(N), where N is the number of nodes in the linked list.
- Storage: O(1), constant extra space.
Code
# 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:
decimal_value = 0
current = head
while current:
decimal_value = (decimal_value * 2) + current.val
current = current.next
return decimal_value