面试题05.02.二进制数转字符串
链接:面试题05.02.二进制数转字符串
难度:Medium
标签:位运算、数学、字符串
简介:二进制数转字符串。给定一个介于0和1之间的实数(如0.72),类型为double,打印它的二进制表达式。
题解 1 - cpp
- 编辑时间:2023-03-02
- 内存消耗:6MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    string printBin(double num) {
        string res = "0.";
        for (int i = 1; i < 32 && num > 0; i++) {
            if (num >= pow(2, -i)) num -= pow(2, -i), res += "1";
            else res += "0";
        }
        if (num) return "ERROR";
        return res;
    }
};
题解 2 - rust
- 编辑时间:2023-03-02
- 内存消耗:2.4MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
        pub fn print_bin(num: f64) -> String {
            let mut num = num;
            let mut res = String::from("0.");
            for i in 1..32 {
                if num == 0.0 {
                    break;
                }
                if num >= 2f64.powf(-i as f64) {
                    num -= 2f64.powf(-i as f64);
                    res.push('1');
                } else {
                    res.push('0');
                }
            }
            if num > 0.0 {
                "ERROR".to_string()
            } else {
                res
            }
        }
    }
题解 3 - python
- 编辑时间:2023-03-02
- 执行用时:28ms
- 内存消耗:14.7MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def printBin(self, num: float) -> str:
        res = "0."
        for i in range(1, 32):
            if num <= 0:
                break
            if num >= pow(2, -i):
                num -= pow(2, -i)
                res += "1"
            else:
                res += "0"
        return "ERROR" if num else res