javarecursion

convert binary to decimal using single linked list and recursive method in java


How we can convert binary to decimal using single linked list and recursive method in java? :-s

Ex:

Input: 1->0->0->NULL

Output: 4


Solution

  • I can think of two ways to solve it:

    1- If length of list is known:

    // To find length of list
    public int length(Node head) {
          int count = 0;
          while(head != null) {
             count++;
             head = head.next;
          }
          return count;
       }
    
    public static int convertWhenLengthIsKnown(Node head, int len) {
          int sum = 0;
          if(head.next != null) {
             sum = convertWhenLengthIsKnown(head.next, len-1);
          }
          return sum + head.data * (int)Math.pow(2,len);
       }
    
    
       // Call this function as below:
    
    convertWhenLengthIsKnown(head, length(head)-1);
    
    1. If we don't want to calculate length, then we can have a sum variable which is globally accessible,

      private static int sum = 0;
      
      public static int convert(Node head,int i) {
      
        if(head.next != null) {
          i = convert(head.next, i);
        }
        sum += head.data * (int)Math.pow(2,i);
        return i+1;
       }
      
      // Call this function as below:
      
      convert(head,0);
      

    Below is the Node class:

    class Node {
       int data;
       Node next;
    
       Node(int data) {
          this.data = data;
       }
    }
    

    Hope It helps you.