Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@happyWinner
Created July 27, 2014 12:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save happyWinner/e3e05b8f3937ce114e49 to your computer and use it in GitHub Desktop.
Save happyWinner/e3e05b8f3937ce114e49 to your computer and use it in GitHub Desktop.
/**
* Given a real number between 0 and 1 (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".
*
* Time Complexity: O(1)
* Space Complexity: O(1)
*/
public class Question5_2 {
public String binaryRepresentation(double value) {
if (value >= 1 || value <= 0) {
return "ERROR";
}
StringBuffer binary = new StringBuffer("0.");
double subtractor = 0.5;
while (binary.length() < 32 && value > 0.0) {
if (value - subtractor >= 0) {
value -= subtractor;
binary.append(1);
} else {
binary.append(0);
}
subtractor /= 2;
}
return value <= 0 ? binary.toString() : "ERROR";
}
public static void main(String[] args) {
Question5_2 question5_2 = new Question5_2();
System.out.println(question5_2.binaryRepresentation(10));
System.out.println(question5_2.binaryRepresentation(-10));
System.out.println(question5_2.binaryRepresentation(0.75));
System.out.println(question5_2.binaryRepresentation(0.125));
System.out.println(question5_2.binaryRepresentation(0.00000000000000000000000125));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment