MCPcopy Index your code
hub / github.com/careercup/ctci / printBinary2

Method printBinary2

java/Chapter 5/Question5_2/Question.java:28–50  ·  view source on GitHub ↗
(double num)

Source from the content-addressed store, hash-verified

26 }
27
28 public static String printBinary2(double num) {
29 if (num >= 1 || num <= 0) {
30 return "ERROR";
31 }
32
33 StringBuilder binary = new StringBuilder();
34 double frac = 0.5;
35 binary.append(".");
36 while (num > 0) {
37 /* Setting a limit on length: 32 characters */
38 if (binary.length() >= 32) {
39 return "ERROR";
40 }
41 if (num >= frac) {
42 binary.append(1);
43 num -= frac;
44 } else {
45 binary.append(0);
46 }
47 frac /= 2;
48 }
49 return binary.toString();
50 }
51
52 public static void main(String[] args) {
53 String bs = printBinary(.125);

Callers 1

mainMethod · 0.95

Calls 3

appendMethod · 0.80
lengthMethod · 0.45
toStringMethod · 0.45

Tested by

no test coverage detected