Created
July 23, 2014 16:05
-
-
Save WOLOHAHA/02e22ab09f60411414dd 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."
This file contains hidden or 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
| package POJ; | |
| public class Main{ | |
| /** | |
| * | |
| * 5.2 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." | |
| * | |
| * | |
| */ | |
| public static void main(String[] args) { | |
| Main so = new Main(); | |
| System.out.println(so.printBinary(0.5)); | |
| } | |
| public String printBinary(double num) { | |
| if (num >= 1 || num <= 0) | |
| return "Error"; | |
| StringBuilder result = new StringBuilder(); | |
| result.append("0."); | |
| while (num > 0) { | |
| if (result.length() >= 32) | |
| return "Error"; | |
| double r = num * 2; | |
| if (r >= 1) { | |
| result.append("1"); | |
| num = r - 1; | |
| } else { | |
| result.append("0"); | |
| num = r; | |
| } | |
| } | |
| return result.toString(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment