Binary representation of a real number
Given a real number between 0 and 7 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR."
Java代码:
public String printBinary(double num) {
if((num <=0) ||(num>1))
return "ERRORS";
StringBuilder binary = new StringBuilder(".");
while(num > 0) {
if(binary.length()>=32)
return "ERRORS";
double r = 2*num;
if(r>=1){
binary.append("1");
num = r -1;
} else {
binary.append("0");
num = r;
}
}
return binary.toString();
}