您的位置:首页 > 其它

Binary Representation

2016-07-21 13:29 357 查看
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"
.

分析:

分成两个部分,整数部分用%和/,小数部分 *2 如果 <1 就为0,基数=基数;大于1,就为1,基数=基数-1

比如:
0.6*2=1.2>0 那么就为1 基数=1.2-1=0.2

0.2*2=0.4<0 那么就为0,基数=0.4

0.4*2=0.8<0,那么就为0,基数=0.8

0.8*2=1.6>0 那么就为1,基数为1.6-1=0.6
:
:
:
:
所以5.6可以表示为:101.1001


public class Solution {
/**
*@param n: Given a decimal number that is passed in as a string
*@return: A string
*/
public String binaryRepresentation(String n) {
int intPart = Integer.parseInt(n.substring(0, n.indexOf('.')));
double decPart = Double.parseDouble(n.substring(n.indexOf('.')));
String intstr = "";
String decstr = "";

if (intPart == 0) intstr += '0';
while (intPart > 0) {
int c = intPart % 2;
intstr = c + intstr;
intPart = intPart / 2;
}
int count = 0;
while (decPart > 0.0 && count <= 32) {
double r = decPart * 2;
if (r >= 1.0) {
decstr += '1';
decPart = r - 1.0;
}else {
decstr += '0';
decPart = r;
}
count++;
}

if (count > 32) return "ERROR";
return decstr.length() > 0? intstr + "." + decstr : intstr;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: