前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >二进制表示小数「建议收藏」

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

作者头像
全栈程序员站长
发布2022-09-20 11:44:04
4930
发布2022-09-20 11:44:04
举报
文章被收录于专栏:全栈程序员必看

二进制表示小数

Table of Contents

1 题目

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

2 方法

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

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

3 思路

负数没有考虑。

代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 二进制表示小数
    • Table of Contents
      • 1 题目
        • 2 方法
          • 3 思路
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档