# Cracking The Coding Interview/Q 5.2

From Software Engineers Wiki

Given a real number between 0 and 1 (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."

## Answer

In floating point representation, each bit has value of 1/2^n.

- First bit: 1/2 = 0.5
- Second bit: 1/4 = 0.25
- Third bit: 1/8 = 0.125
- ......

And the actual number is sume of bit values. So there are many numbers can't be represented by computer accurately. Following is simple python script to do this.

def realToBinary(real): if real == 0.0: return "0" binStr = "" curBitValue = 0.5 bits = 0 bitsLimit = 32 while real != 0.0: if real >= curBitValue: binStr += "1" real -= curBitValue else: binStr += "0" curBitValue /= 2 bits += 1 if (bits == bitsLimit): return binStr + " TOO LONG" return binStr def realToBinaryTest(real): binStr = realToBinary(real) print("{}: {}".format(real, binStr)) def main(): realToBinaryTest(0.75) realToBinaryTest(0.5) realToBinaryTest(0.3) realToBinaryTest(0.2) realToBinaryTest(0.1) main()

Test result:

0.75: 11 0.5: 1 0.3: 01001100110011001100110011001100 TOO LONG 0.2: 00110011001100110011001100110011 TOO LONG 0.1: 00011001100110011001100110011001 TOO LONG