给定一个数将其转换为二进制(均用字符串表示),如果这个数的小数部分不能在 32 个字符之内来精确地表示,则返回 "ERROR"。
string binaryRepresentation(const string& str) {
    string integer;
    string decimal;

    auto pos = str.find_first_of('.');
    
    if (pos == string::npos) {
        integer = str;
    } else {
        integer = str.substr(0, pos);
        decimal = str.substr(pos + 1);
    }
    
    vector<int> vec(integer.size());
    
    for (int i = 0; i < vec.size(); ++i) {
        vec[i] = integer[i] - '0';
    }

    string ret;
    int idx = 0;
    while (idx < vec.size()) {
        char binary_num = ('0' + vec[vec.size() - 1] % 2);
        ret = binary_num + ret;
        for (int i = idx; i < vec.size(); ++i) {
            if (i + 1 < vec.size()) {
                vec[i + 1] += 10 * (vec[i] % 2);
            }
            vec[i] >>= 1;
        }
        if (vec[idx] == 0) {
            ++idx;
        }
    }
    bool all_zero = true;
    for (int i = 0; i < decimal.size(); ++i) {
        if (decimal[i] != '0') {
            all_zero = false;
        }
    }
    if (!all_zero && !decimal.empty()) {
        ret += '.'; 
        vec.resize(decimal.size());
        for (int i = 0; i < vec.size(); ++i) {
            vec[i] = decimal[i] - '0';
        }
        idx = vec.size() - 1;
        int bound = 32;
        while (idx >= 0) {
            for (int i = idx; i >= 0; --i) {
                vec[i] *= 2;
                if (i < idx) {
                    vec[i] += vec[i + 1] / 10;
                    vec[i + 1] %= 10;
                }
            }
            if (vec[0] >= 10) {
                vec[0] %= 10;
                ret += '1';
            } else {
                ret += '0'; 
            }
            if (vec[idx] == 0) {
                --idx;
            }
            if (--bound < 0 ) {
                return "ERROR";
            }
        }
    }
    return ret;
}

shiyang6017
158 声望59 粉丝