zl程序教程

您现在的位置是:首页 >  其他

当前栏目

二进制表示小数「建议收藏」

二进制 建议 收藏 表示 小数
2023-06-13 09:12:58 时间

二进制表示小数

Table of Contents

1 题目

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

2 方法

小数分为整数部分(integer)和小数部分(fraction):

  • 整数部分: 对2取余即可得到个位十位百位…上的二进制值,然后除以2作为新的值,等于0结束。
  • 小数部分: 要乘以2,取其整数部分(0/1),作为十分位,百分位…,然后,取小数部分作为新的值,等于0结束,或者无限循环(本题超过32次结束)。

3 思路

负数没有考虑。

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

Validate

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/168007.html原文链接:https://javaforall.cn