码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode "Binary Representation"

时间:2015-10-04 12:20:18      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:

Not hard to think of a solution. But the key is all details.

class Solution {

public:
    /**
     *@param n: Given a decimal number that is passed in as a string
     *@return: A string
     */
    string binaryRepresentation(string n) {
        size_t pos = n.find(".");
        unsigned long vi = atoi(n.substr(0, pos).c_str());
        double vf = atof(n.substr(pos).c_str());

        //  Int part
        string si;
        while(vi)
        {
            si = ((vi & 1) ? 1 : 0) + si;
            vi >>= 1;
        }
        if(si.empty()) si = "0";
        if(vf == 0.) return si;

        //  Fractional part
        string sf;
        while (vf > 0.0) 
        {
            if (sf.length() > 32) return "ERROR";
            if (vf >= 0.5) {
                sf += 1;
                vf -= 0.5;
            }
            else 
            {
                sf += 0;
            }
            vf *= 2;
         }
        return si + "." + sf;
    }
};

LintCode "Binary Representation"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4854394.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!