CTCI: Ch. 5-2

Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with less than 32 characters, print “ERROR.”
 


#include <iostream>
using namespace std;

string printFloatingBinary(double num)
{
    if(num >=1 || num <= 0)
        return "ERROR. (RANGE ERROR)";
    
    string floatingBinary = "";
    floatingBinary.append("0.");
    while(num >= 0)
    {
        if(floatingBinary.length() >= 32)
        {
            floatingBinary = "ERROR. (" + floatingBinary + ")";
            break;
        }
        int intPart;
        double floatingPart;
        
        intPart = num * 2;
        floatingPart = (num * 2) - intPart;
        floatingBinary += (char)intPart + '0';
        
        num = floatingPart;
        
    }
    return floatingBinary;
}

int main(int argc, const char * argv[])
{
    
    cout<<printFloatingBinary(0.12566)<<endl;
    return 0;
}

 

Leave a Reply