Binary Representation
Given a (decimal - e g 3.72) number that is passed in as a string,return the binary representation that is passed in as a string.If the number can not be represented accurately in binary, print “ERROR”
Example
n = 3.72, return ERROR
n = 3.5, return 11.1
----------------- thinking --------------------------------
http://www.cnblogs.com/EdwardLiu/p/4273813.html
------------------ codes ---------------------------------
class Solution {
public:
/**
*@param n: Given a decimal number that is passed in as a string
*@return: A string
*/
string binaryRepresentation(string n) {
// wirte your code here
//split integer and decimal
size_t npoint = n.find('.');
int integer = 0;
double decimal = 0.0;
if (npoint != string::npos) {
decimal = strtod(n.substr(npoint, n.size()).c_str(), NULL);
integer = atoi(n.substr(0, npoint).c_str());
} else {
integer = atoi(n.c_str());
}
// convert integer part
string intbuf;
if (integer > 0) {
while (integer > 0) {
intbuf.append(integer%2==1?"1":"0");
integer /= 2;
}
reverse(intbuf.begin(), intbuf.end());
} else {
intbuf.append("0");
}
// convert decimal part
string decbuf;
if (decimal > 0.0) {
while (decimal > 0.0) {
if (decbuf.size() > 32) {
return "ERROR";
}
decimal *= 2;
if (decimal >= 1.0) {
decbuf.append("1");
decimal -= 1.0;
} else {
decbuf.append("0");
}
}
}
//combine and return
return decbuf.size() > 0 ? intbuf + "." + decbuf : intbuf;
}
};
No comments:
Post a Comment