File tree 2 files changed +50
-4
lines changed
src/main/java/com/ctci/bitmanipulation
2 files changed +50
-4
lines changed Original file line number Diff line number Diff line change @@ -26,10 +26,10 @@ You can also refer to my [Java Notes](http://java.ramswaroop.me) for a quick ref
26
26
2 . [ Cracking the Coding Interview] ( /src/main/java/com/ctci ) :
27
27
1 . [ Arrays and Strings] ( /src/main/java/com/ctci/arraysandstrings )
28
28
2 . [ Linked Lists] ( /src/main/java/com/ctci/linkedlists )
29
- 3 . [ Recursion and DP ] ( /src/main/java/com/ctci/recursionanddp )
30
- 4 . [ Stacks and Queues ] ( /src/main/java/com/ctci/stacksandqueues )
31
- 5 . [ Trees and Graphs ] ( /src/main/java/com/ctci/treesandgraphs )
32
- 6 . [ Bit Manipulation ] ( /src/main/java/com/ctci/bitmanipulation )
29
+ 3 . [ Stacks and Queues ] ( /src/main/java/com/ctci/stacksandqueues )
30
+ 4 . [ Trees and Graphs ] ( /src/main/java/com/ctci/treesandgraphs )
31
+ 5 . [ Bit Manipulation ] ( /src/main/java/com/ctci/bitmanipulation )
32
+ 6 . [ Recursion and DP ] ( /src/main/java/com/ctci/recursionanddp )
33
33
3 . [ HackerRank] ( /src/main/java/com/hackerrank ) .
34
34
35
35
Original file line number Diff line number Diff line change
1
+ package com .ctci .bitmanipulation ;
2
+
3
+ /**
4
+ * @author rampatra
5
+ * @since 2019-03-16
6
+ */
7
+ public class BinaryToString {
8
+
9
+ /**
10
+ * Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation.
11
+ * If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR."
12
+ *
13
+ * @param realNum a real number between 0 and 1 (for ex. 0.75)
14
+ * @return binary string of the real number
15
+ * @see <a href="http://cs.furman.edu/digitaldomain/more/ch6/dec_frac_to_bin.htm">how to convert decimal fraction to binary</a>
16
+ */
17
+ private static String decimalFractionToBinaryString (double realNum ) {
18
+ if (realNum <= 0 || realNum >= 1 ) {
19
+ return "ERROR" ;
20
+ }
21
+
22
+ int binaryBit ;
23
+ StringBuilder sb = new StringBuilder ();
24
+ sb .append ("0." );
25
+
26
+ while (realNum > 0 ) {
27
+ if (sb .length () == 32 ) {
28
+ return "ERROR" ;
29
+ }
30
+ realNum = realNum * 2 ;
31
+ binaryBit = (int ) realNum ;
32
+ if (binaryBit == 1 ) {
33
+ realNum -= 1 ;
34
+ }
35
+ sb .append (binaryBit );
36
+ }
37
+ return sb .toString ();
38
+ }
39
+
40
+ public static void main (String [] args ) {
41
+ System .out .println (decimalFractionToBinaryString (0.625 ));
42
+ System .out .println (decimalFractionToBinaryString (0.75 ));
43
+ System .out .println (decimalFractionToBinaryString (0.72 ));
44
+ System .out .println (decimalFractionToBinaryString (0.10 ));
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments