Given a (decimal - e g 3.72) number that is passed in as a string, print the binary rep-resentation If the number can not be represented accurately in binary, print “ERROR”
Analysis:
This is a typical example of how to transform a decimal number to binary number. Basic idea is to divide the decimal number into 2 parts, i.e., the int part (e.g. 3), and the decimal part (e.g. 0.72).
For int part, similar approach of extracting numbers from int:
1. use %2 to get each digit from lowest bit to highest bit.
2. int right shift 1 position (=>>1).
3. construct the binary number (always add to the higher position of the current binary number)
Please refer to the code below for the process above.
For decimal part, use *2 approach. For example:
int n = 0.75
n*2 = 1.5
Therefore, the first digit of binary number after '.' is 1 (i.e. 0.1). After constructed the first digit, n= n*2-1 (remaining number would actually be *(2^2) before calculating the next digit)
When the remaining number ==1, the decimal number has been successfully transformed to binary number. Otherwise, the decimal number could not be transform to binary number.
public class Answer {
public static String printBinary(String str){
int intPart = Integer.parseInt(str.substring(0,str.indexOf('.')));
double decPart = Double.parseDouble(str.substring(str.indexOf('.')));
// transform int part to binary
String int_string = "";
while(intPart>0){
int r = intPart%2;
intPart>>=1;
int_string = r+int_string;
}
// transform dec part to binary
StringBuffer dec_string=new StringBuffer();
while(decPart>0){
if(dec_string.length()>32) return "ERROR!";
if(decPart == 1){// exit
dec_string.append((int)decPart);
break;
}
double r = decPart*2;
if(r>=1){
dec_string.append("1");
decPart = r-1;
}
else{
dec_string.append("0");
decPart = r;
}
}
return (int_string + "." + dec_string);
}
public static void main(String[] args) {
String n = "19.25";
String bs = printBinary(n);
System.out.println(bs);
}