Created
August 4, 2014 05:01
-
-
Save bitcpf/525dec151918061e350b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Q5_2 { | |
public static void main(String[] args){ | |
System.out.println(ToBinary(0.72,0)); | |
System.out.println(ToBinary(0.87948723,0)); | |
} | |
public static String ToBinary(double current, int bits){ | |
if(current > 1 || current<0){ | |
return "ERROR"; | |
} | |
StringBuilder result = new StringBuilder(); | |
if(current == 0.5 && bits < 32) { | |
result.append('1'); | |
} | |
else if (current > 0.5){ | |
if(bits > 32){ | |
result.append("Error"); | |
} | |
else { | |
result.append("1"); | |
double temp = (current -0.5)*2; | |
String tempstring = ToBinary(temp,bits+1); | |
result.append(tempstring); | |
} | |
} | |
else{ | |
if(bits > 32){ | |
result.append("t"); | |
return result.toString(); | |
} | |
else{ | |
result.append("0"); | |
double temp = current*2; | |
String tempstring = ToBinary(temp,bits+1); | |
result.append(tempstring); | |
} | |
} | |
if(result.toString().contains("Error")){ | |
return "Error"; | |
} | |
else{ | |
String rettemp = result.toString(); | |
if(rettemp.contains("t")){ | |
return rettemp.replace("t", ""); | |
} | |
else{ | |
return rettemp; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment