LintCode Binary Representation
2015-09-15 00:25
253 查看
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.
Have you met this question in a real interview? Yes
Example
For n = "3.72", return "ERROR".
For n = "3.5", return "11.1".
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 int integer = 0; int pos = 0; int len = n.size(); string res; while (pos < len && n[pos] != '.') { integer = integer * 10 + n[pos] - '0'; pos++; } while (integer) { res.push_back((integer & 0x1) + '0'); integer /= 2; } reverse(res.begin(), res.end()); if (res.empty()) { res.push_back('0'); } int int_part = res.size(); res.push_back('.'); string f = n.substr(pos + 1); int end = f.size(); int count = 0; bool zero = true; for (;end > 0;) { int carry = 0; for (int i = end - 1; i >= 0; i--) { int d = 2 * (f[i] - '0') + carry; f[i] = d % 10 + '0'; carry = d / 10; } res.push_back(carry + '0'); if (carry) { zero = false; } if (++count > 32) { return "ERROR"; } while (end > 0 && f[end - 1] == '0') end--; } if (zero) { return res.substr(0, int_part); } return res; } };
写起来有点啰嗦
相关文章推荐
- 第三章HTML笔记
- ubuntu 上查看内存信息
- linux下rpm,yum学习
- 链栈的基本操作-数据结构
- lammps CUDA 编译
- 为什么需要多线程
- spring boot web相关配置
- Maya Shortcuts 常用快捷键
- spring boot web相关配置
- spring boot web相关配置
- spring boot web相关配置
- TextureView+SurfaceTexture+OpenGL ES来播放视频(二)
- 段落与文字标签
- HTML是什么
- 逆向教程->道具锁定篇①
- 虚函数杂记
- LeetCode Sqrt(x)
- 《我与大数据的365天》 ——(3) 【写代码观察数据变化】
- LeetCode Sqrt(x)
- AndroidStudio安装