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) {
            arr.add(head.val);
            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.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala