首页 > 其他 > 详细

LintCode "Binary Representation"

时间:2015-10-04 12:20:02      阅读:206      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!