lintcode: Binary Representation
来源:互联网 发布:药智数据库官网 编辑:程序博客网 时间:2024/05/17 03:01
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.
Example
For n = “3.72”, return “ERROR”.
For n = “3.5”, return “11.1”.
详解:
1.这题不难,但是调错花了我好长时间。其中有一个错误案例是这样的:
Input
28187281.128121212121
Output
1101011100001101010010001.00100000110011001000110101
Expected
ERROR
错误的原因是我最初将整个字符串用atof转化为double型,再求出整数部分,再减去整数部分得到小数部分。这样得到的小数部分精度就有丢失,导致结果错误。
整数部分和小数部分分别处理就能比较准确的得到数值。
2.关于atof不是很熟。以前一般使用atoi和itoa(itoa现在编译器都不提倡使用)。
没想到atof能够识别“0.1234”“.1234”“-0.1234”这样的小数。
见C++ reference atof
3.关于数字加入到C++字符串的问题。
最初使用stringstream来进行格式转换。
最后发现没有必要,只需要push_back(‘0’+数值)即可。
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 string res=""; int dec_point = n.find("."); int integer_num = atoi( n.substr(0, dec_point).c_str()); double decimal = atof(n.substr(dec_point).c_str()); stack<int> s; if (integer_num == 0){ res +='0'; } while (integer_num){ s.push(integer_num % 2); integer_num /= 2; } while (!s.empty()){ res.push_back('0'+s.top()); s.pop(); } if (decimal > 0.0){ res += '.'; } int cnt = 0; while (decimal>0.0){ if (cnt>32){ return "ERROR"; } decimal *= 2; if (decimal >= 1.0){ res += "1"; decimal -= 1.0; } else{ res += "0"; } cnt++; } return res; }};
- lintcode: Binary Representation
- [LintCode]Binary Representation
- [lintcode]二进制表示 ,Binary Representation
- Chapter 2. Binary and Number Representation
- Binary representation of a given number
- [CrackCode] 5.2 Print the binary representation
- Q5.2 Print the binary representation
- #LintCode# Binary Search
- lintcode Binary Search
- [LintCode]Invert Binary Tree
- lintcode: Balanced Binary Tree
- lintcode:Identical Binary Tree
- lintcode:Binary Tree Serialization
- [Lintcode]Binary Tree Serialization
- LintCode Add Binary 二进制求和
- LintCode Binary Search 二分查找
- lintcode:Binary Tree Preorder Traversal
- lintcode:Validate Binary Search Tree
- Network Interface name change
- sublime学习2:优秀的文本化编辑思想大碰撞(Markdown、LaTeX、MathJax)
- 再谈设计模式之创建型
- UICollectionViewLayout 学习(转)
- 进制转换
- lintcode: Binary Representation
- Jclouds 使用(1)安装
- Echatrs实现水平竖直90度标线及浮动范围和最高值的效果
- CAS 实现单点登录(SSO)基本实现流程(一)
- 4.Redis学习-hash数据类型操作
- swift中调用OC对称加密AES
- 大端模式和小端模式的区别
- C# Lambda Expression概念浅析
- 关于$.ajax()在jsp中失效