Lintcode: Binary Representation
Given a (decimal - e g 3.72) number that is passed in as a string,return the binary representation that is passed in as a string.If the number can not be represented accurately in binary, print “ERROR” Example n = 3.72, return ERROR n = 3.5, return 11.1
For int part, similar approach of extracting numbers from int:
1. use %2 to get each digit from lowest bit to highest bit.
2. int right shift 1 position (=>>1).
3. construct the binary number (always add to the higher position of the current binary number)
Please refer to the code below for the process above.
For decimal part, use *2 approach. For example:
int n = 0.75
n*2 = 1.5
Therefore, the first digit of binary number after '.' is 1 (i.e. 0.1). After constructed the first digit, n= n*2-1