[LintCode]Binary Representation
来源:互联网 发布:英语学习软件有哪些 编辑:程序博客网 时间:2024/05/17 01:28
http://www.lintcode.com/en/problem/binary-representation/
讲一个可能含有小数的十进制String,转成二进制,如果不能转返回ERROR
小数转换就是不断*2,如果乘后大于等于1,则当前位置为1,并且将值减一;否则当前位置为0
public class Solution { /** *@param n: Given a decimal number that is passed in as a string *@return: A string */ public String binaryRepresentation(String s) { // write your code here if (s.indexOf(".") == -1) { return parseInt(s); } String[] params = s.split("\\."); String f = parseFloat(params[1]); if (f.equals("ERROR")) { return f; } String i = parseInt(params[0]); if (f.equals("") || f.equals("0")) { return i; } return i + "." + f; } public String parseInt(String s) { StringBuilder sb = new StringBuilder(); if (s.equals("") || s.equals("0")) { return "0"; } int n = Integer.parseInt(s); while (n > 0) { sb.insert(0, n % 2); n /= 2; } return sb.toString(); } public String parseFloat(String s) { HashSet<Double> set = new HashSet(); Double n = Double.parseDouble("0." + s); StringBuilder sb = new StringBuilder(); while (n > 0) { // 二进制小数位数限制32位 if (sb.length() > 32 || set.contains(n)) { return "ERROR"; } n *= 2; if (n >= 1) { sb.append("1"); n -= 1; } else { sb.append("0"); } } return sb.toString(); }}
0 0
- 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
- Spring Boot使用@SpringBootApplication解惑
- iis8.5下wordpress 404问题
- 错误 V4L2CameraDevice: select timeout
- org.hibernate.HibernateException: No CurrentSessionContext configured!
- selenium2: Click radio button 不生效的解决方法
- [LintCode]Binary Representation
- LRU cache实现
- awt 实现窗口重绘
- PHP时间戳函数总结一览(转)
- tensorflow28《TensorFlow实战Google深度学习框架》笔记-10-05 同步更新模式样例程序 code
- SVN+apache整合
- Python字符编码问题学习
- SVN增量备份一:svnsync
- svnsync问题: have you committed to the destination without using svnsync