25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions to Chapter 5 | Bit Manipulation<br />

5 2 Given a (decimal - e g 3 72) number that is passed in as a string, print <strong>the</strong> binary representation<br />

If <strong>the</strong> number can not be represented accurately in binary, print “ERROR”<br />

SOLUTION<br />

CareerCup com<br />

pg 58<br />

First, let’s start off by asking ourselves what a non-integer number in binary looks like By<br />

analogy to a decimal number, <strong>the</strong> number n = 0 101 = 1 * (1/2^1) + 0 * (1/2^2) + 1 * (1/2^3)<br />

Printing <strong>the</strong> int part of n is straight-forward (see below) To print <strong>the</strong> decimal part, we can<br />

multiply by 2 and check if <strong>the</strong> 2*n is greater than or equal to one This is essentially “shifting”<br />

<strong>the</strong> fractional sum That is:<br />

r = 2*n = 2*0.101 = 1*(1 / 2^0) + 0*(1 / 2^1) + 1*(1 / 2^2) = 1.01<br />

If r >= 1, <strong>the</strong>n we know that n had a 1 right after <strong>the</strong> decimal point By doing this continuously,<br />

we can check every digit<br />

1 public static String printBinary(String n) {<br />

2 int intPart = Integer.parseInt(n.substring(0, n.indexOf(‘.’)));<br />

3 double decPart = Double.parseDouble(<br />

4 n.substring(n.indexOf(‘.’), n.length()));<br />

5 String int_string = “”;<br />

6 while (intPart > 0) {<br />

7 int r = intPart % 2;<br />

8 intPart >>= 1;<br />

9 int_string = r + int_string;<br />

10 }<br />

11 StringBuffer dec_string = new StringBuffer();<br />

12 while (decPart > 0) {<br />

13 if (dec_string.length() > 32) return “ERROR”;<br />

14 if (decPart == 1) {<br />

15 dec_string.append((int)decPart);<br />

16 break;<br />

17 }<br />

18 double r = decPart * 2;<br />

19 if (r >= 1) {<br />

20 dec_string.append(1);<br />

21 decPart = r - 1;<br />

22 } else {<br />

23 dec_string.append(0);<br />

24 decPart = r;<br />

25 }<br />

26 }<br />

27 return int_string + “.” + dec_string.toString();<br />

28 }<br />

1 3 4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!