image

Photo Credit: Pixiv - 七淵

LintCode Solution - Binary Representation

http://www.lintcode.com/en/problem/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 fractional part of the number can not be represented accurately in binary with at most 32 characters, return ERROR.
Example
For n = "3.72", return "ERROR".
For n = "3.5", return "11.1".

Solution

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class Solution {
/**
*@param n: Given a decimal number that is passed in as a string
*@return: A string
*/

public String binaryRepresentation(String n) {
// write your code here
int integer = Integer.parseInt(n.substring(0,n.indexOf('.')));
double fraction = Double.parseDouble(n.substring(n.indexOf('.')));

StringBuilder result = new StringBuilder();
boolean flag = false;

for (int i = 0; i < 32; i++) {
if (!(fraction > 0.0)) {
flag = true;
break;
}
int curry;
fraction = fraction * 2;
curry = (int) fraction / 1;
fraction = fraction - curry;
result.append(String.valueOf(curry));
}

if (flag) {
StringBuilder temp = new StringBuilder();
while (integer != 0) {
temp.append(integer % 2);
integer = integer / 2;
}
return binaryRepresentHelper(temp, result);
} else {
return "ERROR";
}
}
private String binaryRepresentHelper(StringBuilder integer, StringBuilder fraction) {
if (fraction.length() == 0 && integer.length() == 0) {
return "0";
}else if (fraction.length() == 0) {
return integer.reverse().toString();
} else if (integer.length() == 0) {
return "0." + fraction.toString();
} else {
return integer.reverse().toString() + "." + fraction.toString();
}
}
}

ATTENTION

  • float is not available here since Java has taken the first 6 numbers after the point and then rounded up the rest. float is less precise than a double.
  • int integer = Integer.parseInt(n.substring(0,n.indexOf('.')));
  • double fraction = Double.parseDouble(n.substring(n.indexOf('.')));