Created
June 27, 2023 05:33
-
-
Save pmatsinopoulos/875a9514f6660658e4e3d7bfc3c08b6d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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