您的位置:首页 > 其它

LintCode 二进制表示

2015-12-25 21:12 447 查看

LintCode 二进制表示

给定一个数将其转换为二进制(均用字符串表示),如果这个数的小数部分不能在 32 个字符之内来精确地表示,则返回 “ERROR”。

样例

n = “3.72”, 返回 “ERROR”.

n = “3.5”, 返回 “11.1”.

题目很简单,直接上代码吧

public class BinaryRepresention {

/**
* 计算n的二进制表示
* @param n n
* @return n的二进制表示
*/
private static String getIntBin(int n) { //Integer.toBinaryString(n)
StringBuilder res = new StringBuilder();

if (n == 0) return "0";
while(n != 0) {
res.append(n%2);
n /= 2;
}
return  res.reverse().toString();
}

/**
* 计算小数部分的二进制表示
* @param d 要计算的小数
* @return 二进制
*/
private static String getDoubleBin(double d) {
StringBuilder res = new StringBuilder();

if (d == 0) return "0";
while (d != 0.0) {
if (res.length() > 32)
return "ERROR";
double ans = d * 2;
int tmp = (int)ans;
res.append(tmp);
d = ans - tmp;
}

return res.toString();
}

public static String binaryRepresentation(String str) {

if (str.length() == 0)
return "ERROR";

int inter = 0;
double d = 0;
int index = str.indexOf('.');
if (index != -1) { //存在小数
inter = Integer.parseInt(str.substring(0, index));
d = Double.parseDouble(str.substring(index));
} else {
inter = Integer.parseInt(str);
}

StringBuilder res = new StringBuilder();
res.append(getIntBin(inter));
//res.append(".");

if (d == 0)
return res.toString();
res.append(".");
String tmp  = getDoubleBin(d);
if (tmp.equals("ERROR"))
return tmp;

return res.append(tmp).toString();
}

public static void main(String [] args) {
System.out.println(binaryRepresentation("6.125"));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: