I am writing a method to recursively convert an integer value to its binary representation.
The code that I wrote below accomplishes the task by just using a method, but I'd like to know how to actually write out a full method.
import java.util.Scanner;
public class Exercise18_21 {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal integer: ");
int decimal = input.nextInt();
System.out.print("Enter a character: ");
System.out.printf("%d decimal is binary %s",decimal,dec2Bin(decimal));
}
//input: integer
//output: binary representation of integer as a string
public static String dec2Bin(int decimal){
return Integer.toBinaryString(decimal);
}
}
My question is how can this be accomplished with recursion?
CodePudding user response:
I want to preserve your code as mush as I can. Therefore I just add a new method successiveDivision(int)
import java.util.Scanner;
public class Exercise18_21 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a decimal integer: ");
int decimal = input.nextInt();
System.out.print("Enter a character: ");
System.out.printf("%d decimal is binary %s", decimal, dec2Bin(decimal));
}
// input: integer
// output: binary representation of integer as a string
public static String dec2Bin(int decimal) {
return successiveDivision(decimal);
}
public static String successiveDivision(int dec) {
if (dec <= 0) {
return "";
} else {
int bit = dec % 2;
return successiveDivision(dec / 2) bit;
}
}
}
CodePudding user response:
You can implement it the same way you can do it with pen and paper. Use the modulo operation. divided by 2 is your parameter for the recursive call and mod 2 is your current digit.