给定一个数将其转换为二进制(均用字符串表示),如果这个数的小数部分不能在 32 个字符之内来精确地表示,则返回 “ERROR”。
小数分为整数部分(integer)和小数部分(fraction):
负数没有考虑。
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 StringBuffer sbInt = new StringBuffer(); StringBuffer sbFrac = new StringBuffer(); int nInt; double dFrac; int sign; int index = n.indexOf("."); if (index == -1) { nInt = Integer.decode(n); dFrac = 0.0; } else { nInt = Integer.parseInt(n.substring(0, index)); dFrac = Double.parseDouble(n.substring(index)); } while (dFrac != 0.0) { if (sbFrac.length() > 32) { return "ERROR"; } double dFrac2 = 2 * dFrac; int dFrac2_int = (int)dFrac2; dFrac = dFrac2 - dFrac2_int; sbFrac.append(dFrac2_int); } if (nInt < 0) { sign = -1; nInt = -1 * nInt; } while (nInt != 0) { sbInt.append(nInt % 2); nInt /= 2; } if (sbInt.length() == 0) { sbInt.append("0"); } else { sbInt.reverse(); } if (index == -1 || sbFrac.length() == 0) { return sbInt.toString(); } else { return sbInt.append(".").append(sbFrac).toString(); } } }
Date: 2016-12-25 23:08
Created: 2016-12-31 周六 10:22
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/168007.html原文链接:https://javaforall.cn