Decimal to Binary
Completed
Write a recursive static String toBinary(int n) and print the binary form of each input number.
Input
n, then n non-negative integers.
Output
n lines.
Example
Input
3 5 0 255
Output
101 0 11111111
Editor
Java
Hints
The last binary digit is n % 2; the rest is toBinary(n / 2).
Solution explanation
Integer.toBinaryString exists, but writing it recursively shows how the conversion works.
Show solution
import java.util.Scanner;
public class Main {
static String toBinary(int n) {
if (n < 2) {
return String.valueOf(n);
}
return toBinary(n / 2) + (n % 2);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.println(toBinary(sc.nextInt()));
}
}
}