二进制表示

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

样例

n = "3.72", 返回 "ERROR".

n = "3.5", 返回 "11.1".

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
        int intPart = atoi(n.c_str());
        double decPart = atof(n.c_str());
        decPart -= intPart;

        string intStr;
        string decStr;

        if (intPart == 0)
        {
            intStr += '0';
        }
        while (intPart > 0)
        {
            int c = intPart % 2;
            intStr = (char)(c+'0') + intStr;
            intPart /= 2;
        }

        while (decPart > 0.0)
        {
            if (decStr.length() > 32) 
            {
                return "ERROR";
            }
            double r = decPart * 2;
            if (r >= 1.0)
            {
                decStr += '1';
                decPart = r - 1.0;
            }
            else
            {
                decStr += '0';
                decPart = r;
            }
        }

        return decStr.length() > 0? intStr + "." + decStr : intStr;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值