您的位置:首页 > 其它

二进制表示-LintCode

2017-08-24 17:10 253 查看
给定一个数将其转换为二进制(均用字符串表示),如果这个数的小数部分不能在 32 个字符之内来精确地表示,则返回 “ERROR”。

样例:

n = “3.72”, 返回 “ERROR”.

n = “3.5”, 返回 “11.1”.

#ifndef C180_H
#define C180_H
#include<iostream>
#include<string>
using namespace std;
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
if (n.empty())
return NULL;
int len = n.size();
int pos = 0;
for (int i = 0; i < len; ++i)
{
if (n[i] == '.')
{
pos = i;
break;
}
}
string Integer = n.substr(0,pos);
string Decimal = n.substr(pos + 1, len - 1 - pos);
int size = Decimal.size();
long long intNum = stoll(Integer);
long long DecNum = stoll(Decimal);
double num = DecNum;

for (int j = 1; j <= size; ++j)
{
num /= 10;
}

int count = 0;
string sum;
while (num != 0)
{
count++;
num *= 2;
if (num >= 1)
{
num -= 1;
sum += "1";
}
else
{
sum += "0";
}
}
if (count > 32)
return "ERROR";
else
{
string str;
if (intNum == 0)
str= "0";
for (int i = intNum; i; i = i / 2)
{
str += (i % 2 ? "1" : "0");
}
reverse(str.begin(), str.end());
if (sum.empty())
return str;
return str + "." + sum;
}
}
};
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: