-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathBinaryToString.java
More file actions
33 lines (30 loc) · 898 Bytes
/
BinaryToString.java
File metadata and controls
33 lines (30 loc) · 898 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package bits;
/**
* Given a real number between 0 & 1 (eg. 0.72) that is passed in as double, print the binary representation.
* If # cannot be expressed in binary with at most 32 bits, then throw ERROR.
*/
class BinaryToString {
public static void main(String[] args) {
System.out.println(binary(0.04));
}
static String binary(double num) {
if (num > 1 && num < 0) {
throw new RuntimeException("ERROR");
}
StringBuilder b = new StringBuilder(".");
while (num > 0) {
// if (b.length() >= 32) {
// throw new RuntimeException("ERROR");
// }
double r = num * 2;
if (r >= 1) {
b.append(1);
num = r - 1;
} else {
b.append(0);
num = r;
}
}
return b.toString();
}
}