Skip to content

Instantly share code, notes, and snippets.

@pmatsinopoulos
Created June 27, 2023 05:33
Show Gist options
  • Save pmatsinopoulos/875a9514f6660658e4e3d7bfc3c08b6d to your computer and use it in GitHub Desktop.
Save pmatsinopoulos/875a9514f6660658e4e3d7bfc3c08b6d to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class IntegerToBinaryRecursive {
/**
* Given an integer N, its binary representation is
* the binary representation of N/2 suffixed with the modulo of N % 2
*/
public static String toBinary(int integer) {
if (integer <= 1) {
return Integer.toString(integer);
}
String result = toBinary(integer / 2) + Integer.toString(integer % 2);
return result;
}
public static void main(String[] args) {
System.out.print("Give me an integer and I will give you back its binary representation: ");
Scanner scanner = new Scanner(System.in);
if (scanner.hasNextInt()) {
int integer = scanner.nextInt();
System.out.printf("Binary representation of %d: is %s\n", integer, toBinary(integer));
}
scanner.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment