Java Program to Convert Integer to Binary using Recursion

// The following code illustrates how to convert an Integer to Binary using Recursion. We can also convert an integer to Binary using the toBinaryString(number) method using Integer Class.




import java.util.Scanner;

class binary {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Please enter Integer");

int number = sc.nextInt();

System.out.println("Using toBinaryString(number) Binary of " +number + " is " + Integer.toBinaryString(number)); // Convers Integer to Binary using toBinaryString(number) method...

String binary=binary(number);

System.out.println("Using Recursion Binary of " +number + " is " + binary);

}

// The Following Recursive function converts Integer to Binary...

public static String binary (int num)
{

if (num==0) return "0"; else if (num==1) return "1";
else if (num<0) return ("-" + binary(-num));
else return( binary(num/2 ) +( char) ((num%2) +48)); }
}


In the above function ((num%2) +48) gives the ascii value of a digit . (char) ((num%2) +48) converts ascii to char ( for example ascii value 48 is equal to digit 1 , 49-> 1)


Output :

Running the above program

D:\as2\JF1>java binary
Please enter Integer
10
Using toBinaryString(number) Binary of 10 is 1010
Using Recursion Binary of 10 is 1010

D:\as2\JF1>java binary
Please enter Integer
100
Using toBinaryString(number) Binary of 100 is 1100100
Using Recursion Binary of 100 is 1100100

D:\as2\JF1>java binary
Please enter Integer
25
Using toBinaryString(number) Binary of 25 is 11001
Using Recursion Binary of 25 is 11001

0 comments:

Post a Comment

 
Copyright 2011 Java Online