In: Computer Science
JAVA Language: Write a program that prompts the user to enter a positive integer n (0 up to 232 -1). You must write a function that takes as input n and returns a string s representing the number n in binary. For this assignment, you must use the method of successive division by 2 to convert the number to binary. Your main program must print out s. Example: If the user enters the number 66, your program must print out 1000010.
import java.util.Scanner; public class DecimalToBinary { public static String convertToBinary(int n) { if(n == 0) return "0"; String binary = ""; while (n > 0) { binary = (n % 2) + binary; n /= 2; } return binary; } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a decimal number: "); int n = in.nextInt(); System.out.println(n + " in binary is " + convertToBinary(n)); in.close(); } }