Write a Java method with the following header public static
Write a Java method with the following header:
public static void binaryPrint (int n)
The number n is non-negative. The method prints the value of n as a binary number. If n is zero, then a single zero is printed; otherwise, no leading zeros are printed in the output. The \'\ \' character is NOT printed at the end of the output. Your implementation must be recursive and not use any local variables.
Examples:
n=0 Output: 0
n=4 Output: 100
n=27 Output: 11011
Solution
DecimalConverter.java
import java.util.Scanner;
public class DecimalConverter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(\"Please enter a decimal number:\");
int n = scan.nextInt();
binaryPrint(n);
}
public static void binaryPrint(int n){
System.out.println(\"The binary value of \"+n+\" is \");
do {
System.out.print(n & 1);
n = n >> 1;
} while (n > 0);
}
}
Output:
Please enter a decimal number:
27
The binary value of 27 is
11011
