LintCode "Binary Representation"
2015-10-04 11:54
239 查看
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; } };
相关文章推荐
- hdu1754 I hate it线段树模板 区间最值查询
- 证券基础--股票发行方式
- Odoo9发行说明
- 软件工程之面向过程的软件设计方法(二)
- J2EE学习路线
- 深入详解保护模式下的内存分页机制
- 证书
- andriod 实现新浪、QQ场地、朋友微信圈、微信朋友分享功能
- DirectX11 雾
- Hbase笔记二:简明系统架构
- 获取函数或程序相关的源码
- Matrix学习
- 经典算法题——第十三题 赫夫曼树
- MyEclipse 2014 破解图文详细教程
- Hbase笔记一:了解Hbase
- Java中有关Null的9件事
- 96. Unique Binary Search Trees (Tree; DFS)
- Asp.Net MVC 使用 DataAnnotations 进行模型验证
- 错误 10 非静态的字段、方法或属性“Test10.Program.a”要求对象引用
- HDU 1015 爆搜 /dfs+回溯