Categories
Class 11 Class 12

Convert Binary to Decimal using Recursion

Write a program in Java to accept a binary number and convert it into its decimal equivalent using recursive function. Display a suitable message if the binary number is negative and if it does not contain 1s and 0s.

Example:
Sample Input:
Enter a binary number: 110011
Sample Output:
The decimal equivalent: 51

import java.io.*;
class BinaryToDecimal{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Binary integer: ");
        int bin = Integer.parseInt(br.readLine());
        if(!valid(bin)){
            System.out.println("Invalid Binary Number!");
            return;
        }
        int d = convert(bin, 0);
        System.out.println("Decimal equivalent = " + d);
    }
    public static boolean valid(int bin){
        String b = Integer.toString(bin);
        if(b.length() == 0)
            return false;
        for(int i = 0; i < b.length(); i++){
            if(b.charAt(i) != '1' && b.charAt(i) != '0')
                return false;
        }
        return true;
    }
    public static int convert(int b, int p){
        if(b == 0)
            return 0;
        if(b == 1)
            return (int)Math.pow(2, p);
        return b % 10 * (int)Math.pow(2, p) + convert(b / 10, p + 1);
    }
}

2 replies on “Convert Binary to Decimal using Recursion”

Leave a Reply