lintcode: Binary Representation

来源:互联网 发布:药智数据库官网 编辑:程序博客网 时间:2024/05/17 03:01

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
原创粉丝点击