Convert an Integer to Binary in Java

Write a recursive function to convert an integer to its binary equivalent and return it.

Program:

import java.io.*;
class Binary{
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Enter the integer: ");
        int n = Integer.parseInt(br.readLine());
        long b = getBinary(n);
        System.out.println("Binary equivalent: " + b);
    }
    public static long getBinary(int n){
        if(n == 0)
            return 0L;
        else{
            int rem = n % 2;
            return rem + getBinary(n / 2) * 10L;
        }
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.