码迷,mamicode.com
首页 > 其他好文 > 详细

Cracking the Coding Interview 5.2

时间:2014-08-19 22:04:15      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   art   div   

Given a(decimal -e.g. 3.72)number that is passed in as a string, print the binary representation. If the number can not be represented accurately in binary, print "ERROR"

 

整数部分:

    对2取余,然后向右移动一位,重复直到整数部分变为0

小数部分:

    乘以2,看结果是否大于1,大于1则2^-1位上位1,否则为0。如果大于1,将结果减1再乘以2,否则直接乘以2,继续判断,直到小数部分超过32位,返回ERROR

    例如:0.75d = 0.11b,乘以2实际上相当于左移,结果大于1,则说明2^-1位上是1,然后减1,继续乘以2,结果等于1,说明2^-2上是1,且后面没有小数了。

#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;

string func(const string &str)
{
    string strInt;
    string strDou;

    string::size_type idx = str.find(.);    
    if(idx == string::npos)
    {
        strInt = str;
    }
    else
    {
        strInt = str.substr(0,idx);
        strDou = str.substr(idx);
    }

    int intPart = atoi(strInt.c_str());
    double douPart;
    if(!strDou.empty())
    {
        douPart = atof(strDou.c_str());
    }
    else
    {
        douPart = 0.0;
    }

    string strIntB,strDouB;
    while(intPart!=0)
    {
        if((intPart&1)>0)
        {
            strIntB = 1+strIntB;
        }
        else
        {
            strIntB = 0+strIntB;
        }
        intPart=intPart>>1;
    }
    while(!(douPart>-10e-15 && douPart<10e-15))
    {
        if(douPart*2>1)
        {
            strDouB = 1+strDouB;
            douPart = douPart*2-1;
        }

        else if((douPart*2-1)>-10e-15 && (douPart*2-1)<10e-15)
        {
            strDouB = 1+strDouB;
            break;
        }

        else
        {
            strDouB = 0+strDouB;
        }
        if(strDouB.size()>32)
        {
            return "ERROR";
        }
    }

    if(strDouB.empty())
    {
        return strIntB;
    }
    else
    {
        return (strIntB+.+strDouB);
    }
}

int main()
{
    string str("3.75");
    cout<<func(str)<<endl;
    return 0;
}

 

Cracking the Coding Interview 5.2,布布扣,bubuko.com

Cracking the Coding Interview 5.2

标签:style   blog   color   os   io   ar   art   div   

原文地址:http://www.cnblogs.com/johnsblog/p/3923016.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!