Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
    }
};
posted on 2015-10-04 11:54  Tonix  阅读(154)  评论(0编辑  收藏  举报