Skip to content

Instantly share code, notes, and snippets.

@UncleGarden
Created July 28, 2014 08:34
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save UncleGarden/6c4e61c377da227fd4ff to your computer and use it in GitHub Desktop.
CareerCup 150
/**
*
* 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