[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
原创粉丝点击