-----------> This code needs to have the binary function handle a negative numbe
ID: 3801917 • Letter: #
Question
-----------> This code needs to have the binary function handle a negative number.
import java.util.Scanner;
public class BinaryTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a deciaml number: ");
int binaryNumber = scan.nextInt();
System.out.println("Binary String is "+binary(binaryNumber));
}
public static String binary(int binaryNumber){
if(binaryNumber<=0){
return "Invalid Input. Input must be greather than 0.";
}
String s = "";
do {
s = s + (binaryNumber & 1);
binaryNumber = binaryNumber >> 1;
} while (binaryNumber > 0);
return new StringBuffer(s).reverse().toString();
}
}
Explanation / Answer
import java.util.Scanner;
public class BinaryTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a deciaml number: ");
int binaryNumber = scan.nextInt();
System.out.println("Binary String is " + binary(binaryNumber));
}
public static String binary(int binaryNumber) {
if (binaryNumber <= 0) {
return Integer.toBinaryString(binaryNumber);
}
else
{
String s = "";
do {
s = s + (binaryNumber & 1);
binaryNumber = binaryNumber >> 1;
} while (binaryNumber > 0);
return new StringBuffer(s).reverse().toString();
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.