[LintCode]Binary Representation

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值