zoukankan      html  css  js  c++  java
  • 二进制小数 牛客网 程序员面试金典 C++ Python

    二进制小数 牛客网 程序员面试金典

    • 题目描述

    • 有一个介于0和1之间的实数,类型为double,返回它的二进制表示。如果该数字无法精确地用32位以内的二进制表示,返回“Error”。

    • 给定一个double num,表示0到1的实数,请返回一个string,代表该数的二进制表示或者“Error”。

    • 测试样例:

    • 0.625

    • 返回:0.101

    C++

    class BinDecimal {
    public:
        //run:3ms memory:484k
        string printBin(double num) {
            string str("0.");
            double base = 0.5;
            for(;num >0; base /=2){
                if (num >= base){
                    num -= base;
                    str += "1";
                }else str += "0";
                if(str.size() > 32) return str = "Error";
            }
            return str;
        }
        //run:3ms memory:476k
        string printBin2(double num) {
            string str("0.");
            double base = 0.5;
            while(num > 0){
                if(num >= base){
                    num -= base;
                    str += "1";
                }
                else 
                    str += "0";
                base /= 2;
                if(str.size() > 32) 
                    return str = "Error";
            }
            return str;
        }
    };

    Python

    class BinDecimal:
        def printBin(self, num):
            lt = ["0","."]
            base = 0.5
            while num > 0:
                if num >= base:
                    num -= base;
                    lt.append("1")
                else:
                    lt.append("0")
                base /= 2
                if len(lt) >=32: return "Error"
            return ''.join(lt)
        
        def printBin2(self, num):
            if num >= 1 or num <= 0:
                return "Error"
            binary = ['0', '.']
            while num > 0:
                if len(binary) >= 32:
                    return "Error"
                r = num * 2
                if r >= 1:
                    binary.append('1')
                    num = r - 1
                else:
                    binary.append('0')
                    num = r
            return ''.join(binary)
  • 相关阅读:
    hiveserver2 with kerberos authentication
    python Basic usage
    python Quicksort demo
    Python HeapSort
    mrunit for wordcount demo
    CCDH证书
    Hadoop question list
    Hadoop Yarn core concepts
    Hadoop Resource
    Hadoop could not find or load main class
  • 原文地址:https://www.cnblogs.com/vercont/p/10210336.html
Copyright © 2011-2022 走看看