Given a real number between O and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print "ERROR".
Example1:
Input: 0.625
Output: "0.101"
Example2:
Input: 0.1
Output: "ERROR"
Note: 0.1 cannot be represented accurately in binary.
Note:
- This two characters "0." should be counted into 32 characters.
The method of converting a decimal fraction to a binary fraction is as follows: multiply the decimal part by
Let's take an example, suppose we want to convert
So the binary fraction representation of the decimal fraction
For this problem, since the real number is between
Finally, if the decimal part is not "ERROR"
. Otherwise, return the converted binary fraction.
The time complexity is
class Solution:
def printBin(self, num: float) -> str:
ans = '0.'
while len(ans) < 32 and num:
num *= 2
x = int(num)
ans += str(x)
num -= x
return 'ERROR' if num else ans
class Solution {
public String printBin(double num) {
StringBuilder ans = new StringBuilder("0.");
while (ans.length() < 32 && num != 0) {
num *= 2;
int x = (int) num;
ans.append(x);
num -= x;
}
return num != 0 ? "ERROR" : ans.toString();
}
}
class Solution {
public:
string printBin(double num) {
string ans = "0.";
while (ans.size() < 32 && num != 0) {
num *= 2;
int x = (int) num;
ans.push_back('0' + x);
num -= x;
}
return num != 0 ? "ERROR" : ans;
}
};
func printBin(num float64) string {
ans := &strings.Builder{}
ans.WriteString("0.")
for ans.Len() < 32 && num != 0 {
num *= 2
x := byte(num)
ans.WriteByte('0' + x)
num -= float64(x)
}
if num != 0 {
return "ERROR"
}
return ans.String()
}