您的位置:首页 > 其它

LintCode Binary Representation

2015-09-15 00:25 253 查看

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 fractional part of the number can not be represented accurately in binary with at most 32 characters, return ERROR.

Have you met this question in a real interview? Yes

Example

For n = "3.72", return "ERROR".

For n = "3.5", return "11.1".


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
int integer = 0;
int pos = 0;
int len = n.size();
string res;
while (pos < len && n[pos] != '.') {
integer = integer * 10 + n[pos] - '0';
pos++;
}
while (integer) {
res.push_back((integer & 0x1) + '0');
integer /= 2;
}
reverse(res.begin(), res.end());

if (res.empty()) {
res.push_back('0');
}
int int_part  = res.size();
res.push_back('.');

string f = n.substr(pos + 1);
int end = f.size();
int count = 0;
bool zero = true;
for (;end > 0;) {
int carry = 0;
for (int i = end - 1; i >= 0; i--) {
int d = 2 * (f[i] - '0') + carry;
f[i] = d % 10 + '0';
carry = d / 10;
}
res.push_back(carry + '0');
if (carry) {
zero = false;
}
if (++count > 32) {
return "ERROR";
}
while (end > 0 && f[end - 1] == '0') end--;
}
if (zero) {
return res.substr(0, int_part);
}
return res;
}

};

写起来有点啰嗦
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: