LeetCode - Convert Binary Number in a Linked List to Integer Solution - The Coding Shala

Home >> LeetCode >> convert binary number in a linked list to integer

 In this post, we will learn how to solve LeetCode's Convert Binary Number in a Linked List to Integer problem and will implement Java Solution.

Convert Binary Number in a Linked List to Integer Problem

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.

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

Example 3:
Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
Output: 18880

Convert Binary Number in a Linked List to Integer Java Solution

Approach 1:
We can solve this using extra memory. First will take all data from the linked list and move to ArrayList then we can change it to decimal.

Java Program: 

 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
class Solution {
    public int getDecimalValue(ListNode head) {
        ArrayList<Integer> arr = new ArrayList<>();
        while(head != null) {
            head = head.next;
        int len = arr.size();
        int dec = 0;
        int two = 1;
        for(int i = len-1; i>=0; i--) {
            dec += (arr.get(i) * two);
            two *= 2;
        return dec;

Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.


Popular Posts from this Blog

Basic Structure of C++ Program - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

First Unique Character in a String Java - The Coding Shala