lintcode: Binary Representation

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.
Example
For n = “3.72”, return “ERROR”.
For n = “3.5”, return “11.1”.

详解:
1.这题不难,但是调错花了我好长时间。其中有一个错误案例是这样的:

Input
28187281.128121212121
Output
1101011100001101010010001.00100000110011001000110101
Expected
ERROR

错误的原因是我最初将整个字符串用atof转化为double型,再求出整数部分,再减去整数部分得到小数部分。这样得到的小数部分精度就有丢失,导致结果错误。
整数部分和小数部分分别处理就能比较准确的得到数值。

2.关于atof不是很熟。以前一般使用atoi和itoa(itoa现在编译器都不提倡使用)。
没想到atof能够识别“0.1234”“.1234”“-0.1234”这样的小数。
见C++ reference atof

3.关于数字加入到C++字符串的问题。
最初使用stringstream来进行格式转换。
最后发现没有必要,只需要push_back(‘0’+数值)即可。

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

        string res="";

        int dec_point = n.find(".");

        int integer_num = atoi( n.substr(0, dec_point).c_str());

        double decimal = atof(n.substr(dec_point).c_str());

        stack<int> s;

        if (integer_num == 0){
            res +='0';
        }

        while (integer_num){
            s.push(integer_num % 2);
            integer_num /= 2;
        }

        while (!s.empty()){
            res.push_back('0'+s.top());
            s.pop();
        }

        if (decimal > 0.0){
            res += '.';
        }

        int cnt = 0;

        while (decimal>0.0){
            if (cnt>32){
                return "ERROR";
            }
            decimal *= 2;
            if (decimal >= 1.0){
                res += "1";
                decimal -= 1.0;
            }
            else{
                res += "0";
            }
            cnt++;

        }

        return res;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值