zoukankan      html  css  js  c++  java
  • 二进制表示小数

    二进制表示小数

    二进制表示小数

    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

  • 相关阅读:
    js保存图片至本地
    ArrayLike
    key的作用
    react Video event
    react中字符串换行
    react打包后找不到静态文件
    2020软件工程第三次作业
    003 Longest Substring Without Repeating Characters
    002addTwoNumbers
    001twoSum
  • 原文地址:https://www.cnblogs.com/yangwen0228/p/6221033.html
Copyright © 2011-2022 走看看