CareerCup 150
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
/** | |
* | |
* 5.2 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." | |
* | |
* @author Garden | |
*/ | |
public class CC5_2 { | |
public static String binary(double num) { | |
if (num >= 1 || num <= 0) { | |
return "ERROR"; | |
} | |
StringBuilder sb = new StringBuilder(); | |
sb.append("."); | |
while (num > 0) { | |
if (sb.length() > 32) { | |
return "ERROR"; | |
} | |
double r = num * 2; | |
if (r >= (double)1) { | |
sb.append(1); | |
num = r - 1; | |
} else { | |
sb.append(0); | |
num = r; | |
} | |
} | |
return new String(sb); | |
} | |
public static void main(String[] args) { | |
System.out.println(binary(0.72)); | |
System.out.println(binary(0.5)); | |
System.out.println(binary(0.1)); | |
System.out.println(binary(0.15625)); | |
System.out.println(binary(0.75)); | |
System.out.println(binary(0.87948723)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment