1290. Convert Binary Number in a Linked List to Integer LeetCode Solution

In this guide, you will get 1290. Convert Binary Number in a Linked List to Integer LeetCode Solution with the best time and space complexity. The solution to Convert Binary Number in a Linked List to Integer problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Convert Binary Number in a Linked List to Integer solution in C++
  4. Convert Binary Number in a Linked List to Integer solution in Java
  5. Convert Binary Number in a Linked List to Integer solution in Python
  6. Additional Resources
1290. Convert Binary Number in a Linked List to Integer LeetCode Solution image

Problem Statement of Convert Binary Number in a Linked List to Integer

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.

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

1290. Convert Binary Number in a Linked List to Integer LeetCode Solution in C++

class Solution {
 public:
  int getDecimalValue(ListNode* head) {
    int ans = 0;

    for (; head; head = head->next)
      ans = ans * 2 + head->val;

    return ans;
  }
};
/* code provided by PROGIEZ */

1290. Convert Binary Number in a Linked List to Integer LeetCode Solution in Java

class Solution {
  public int getDecimalValue(ListNode head) {
    int ans = 0;

    for (; head != null; head = head.next)
      ans = ans * 2 + head.val;

    return ans;
  }
}
// code provided by PROGIEZ

1290. Convert Binary Number in a Linked List to Integer LeetCode Solution in Python

class Solution:
  def getDecimalValue(self, head: ListNode) -> int:
    ans = 0

    while head:
      ans = ans * 2 + head.val
      head = head.next

    return ans
# code by PROGIEZ

Additional Resources

See also  1278. Palindrome Partitioning III LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.