给定一个数将其转换为二进制(均用字符串表示),如果这个数的小数部分不能在 32 个字符之内来精确地表示,则返回 "ERROR"
。
样例
n = "3.72"
, 返回 "ERROR"
.
n = "3.5"
, 返回 "11.1"
.
*******************************************************************************
好久没做题 有点懵逼 根据数据试出来的……卧槽……
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
String[] str = n.split("\\.");
if(str.length == 0)
return "ERROR";
if(str.length == 1){
int a = Integer.parseInt(str[0]);
StringBuffer sb = new StringBuffer();
while(a != 0){
sb.append(a%2);
a /= 2;
}
return sb.reverse().toString();
}
if(str.length == 2){
if(str[0].equals("0") && str[1].equals("0"))
return "0";
if(str[0].equals("0")){
StringBuffer sb = new StringBuffer();
sb.append("0.");
double d = Double.parseDouble(n);
while(d != 0.0){
if(sb.length() > 32 )
return "ERROR";
double d_ = d * 2;
int a = (int)d_;
sb.append(a);
d = d_ - a;
}
return sb.toString();
}else{
int a = Integer.parseInt(str[0]);
StringBuffer sb = new StringBuffer();
while(a != 0){
sb.append(a%2);
a /= 2;
}
sb.reverse();
if (!str[1].equals("0"))
sb.append(".");
double d = Double.parseDouble("0."+str[1]);
int num = 0;
while(d != 0.0){
num++;
if(num > 32)
return "ERROR";
double d_ = d * 2;
int x = (int)d_;
sb.append(x);
d = d_ - x;
}
return sb.toString();
}
}
return "ERROR";
}
}