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(0, pos).c_str()); double vf = atof(n.substr(pos).c_str()); // Int part string si; while(vi) { si = ((vi & 1) ? '1' : '0') + si; vi >>= 1; } if(si.empty()) si = "0"; if(vf == 0.) return si; // Fractional part string sf; while (vf > 0.0) { if (sf.length() > 32) return "ERROR"; if (vf >= 0.5) { sf += '1'; vf -= 0.5; } else { sf += '0'; } vf *= 2; } return si + "." + sf; } };