LintCode "Binary Representation"

时间:2023-03-09 09:41:03
LintCode "Binary Representation"

Not hard to think of a solution. But the key is all details.

class Solution {

public:
/**
*@param n: Given a decimal number that is passed in as a string
*@return: A string
*/
string binaryRepresentation(string n) {
size_t pos = n.find(".");
unsigned long vi = atoi(n.substr(, pos).c_str());
double vf = atof(n.substr(pos).c_str()); // Int part
string si;
while(vi)
{
si = ((vi & ) ? '' : '') + si;
vi >>= ;
}
if(si.empty()) si = "";
if(vf == .) return si; // Fractional part
string sf;
while (vf > 0.0)
{
if (sf.length() > ) return "ERROR";
if (vf >= 0.5) {
sf += '';
vf -= 0.5;
}
else
{
sf += '';
}
vf *= ;
}
return si + "." + sf;
}
};