-
-
Save happyWinner/e3e05b8f3937ce114e49 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
/** | |
* 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