The file below is the starter file for the question: import java.util.Scanner; p
ID: 3813822 • Letter: T
Question
The file below is the starter file for the question:
import java.util.Scanner;
public class DecToBin {
public static void main(String[] args) {
System.out.println("Please enter the decimal representation of an integer: ");
Scanner input = new Scanner(System.in);
int decimal = input.nextInt();
String binary = decToBin(decimal);
System.out.printf("The binary representation is %s ", binary);
input.close();
}
public static String decToBin(int decimal) {
// Your code here
In the file, provide code for the method
public static String decToBin(int decimal)
that takes the decimal representation of a nonnegative integer as an int and returns the binary representation of the given integer as a string.
Run the program to test the correctness of your code for the method. The following are some sample runs:
Please enter the decimal representation of an integer:
The binary representation is 10101
Please enter the decimal representation of an integer:
The binary representation is 100001011100
Please also provide comments for each line of the program.
must also be written in java C++
Explanation / Answer
Hi, Please find my implementation.
import java.util.Scanner;
public class DecToBin {
public static void main(String[] args) {
System.out.println("Please enter the decimal representation of an integer: ");
Scanner input = new Scanner(System.in);
int decimal = input.nextInt();
String binary = decToBin(decimal);
System.out.printf("The binary representation is %s ", binary);
input.close();
}
public static String decToBin(int number) {
// Your code here
StringBuffer sBuf = new StringBuffer();
int temp=0;
while(number>0){
temp = number%2;
sBuf.append(temp);
number = number / 2;
}
return sBuf.reverse().toString();
}
}
/*
Sample run:
Please enter the decimal representation of an integer:
123
The binary representation is 1111011
Please enter the decimal representation of an integer:
64
The binary representation is 1000000
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.