-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary Representation.cpp
58 lines (50 loc) · 1.82 KB
/
Binary Representation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
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.
Link: http://www.lintcode.com/en/problem/binary-representation/
Example:
For n = "3.72", return "ERROR".
For n = "3.5", return "11.1".
Solution: The main problem is how the compute represent to float number. For the part less than 1,
we use it to multiply 2, and once its result is greater than 1, we set 1 in the binary (then minus 1),
else is 0.
Source: https://github.com/kamyu104/LintCode/blob/master/C%2B%2B/binary-representation.cpp
*/
class Solution {
public:
/**
*@param n: Given a decimal number that is passed in as a string
*@return: A string
*/
string binaryRepresentation(string n) {
int int_part = stoi(n.substr(0, n.find('.')));
double dec_part = stod(n.substr(n.find('.')));
string int_str = "";
string dec_str = "";
if (int_part == 0) {
int_str.push_back('0');
}
while (int_part > 0) {
int c = int_part % 2;
int_str.push_back('0' + c);
int_part = int_part >> 1;
}
reverse(int_str.begin(), int_str.end());
while (dec_part > 0.0) {
if (dec_str.length() > 32) {
return "ERROR";
}
double remain = dec_part * 2;
if (remain >= 1.0) {
dec_str.push_back('1');
dec_part = remain - 1.0;
}
else {
dec_str.push_back('0');
dec_part = remain;
}
}
return dec_str.length() > 0? int_str + "." + dec_str : int_str;
}
};