LintCode 二进制表示

给定一个数将其转换为二进制(均用字符串表示),如果这个数的小数部分不能在 32 个字符之内来精确地表示,则返回 "ERROR"

样例

n = "3.72", 返回 "ERROR".

n = "3.5", 返回 "11.1".

*******************************************************************************

好久没做题 有点懵逼  根据数据试出来的……卧槽…… 



public class Solution {
    /**
     *@param n: Given a decimal number that is passed in as a string
     *@return: A string
     */
    public String binaryRepresentation(String n) {
        // write your code here
       String[] str = n.split("\\.");
	    	if(str.length == 0)
	    		return "ERROR";
	    	if(str.length == 1){
				int a = Integer.parseInt(str[0]);
				StringBuffer sb = new StringBuffer();
				while(a != 0){
					sb.append(a%2);
					a /= 2;
				}
				return sb.reverse().toString();
	    	}
	    	if(str.length == 2){
	    	    if(str[0].equals("0") && str[1].equals("0"))
	    			return "0";
	    		if(str[0].equals("0")){
	    			StringBuffer sb = new StringBuffer();
	    			sb.append("0.");
	    			double d = Double.parseDouble(n);
	    			while(d != 0.0){
	    				if(sb.length() > 32 )
	    					return "ERROR";
	    				double d_ = d * 2;
	    				int a = (int)d_;
	    				sb.append(a);
	    				d = d_ - a;
	    			}
	    			return sb.toString();
	    		}else{
	    			int a = Integer.parseInt(str[0]);
					StringBuffer sb = new StringBuffer();
					while(a != 0){
						sb.append(a%2);
						a /= 2;
					}
					sb.reverse();
				if (!str[1].equals("0"))
					sb.append(".");
					double d = Double.parseDouble("0."+str[1]);
					int num = 0;
	    			while(d != 0.0){
	    				num++;
	    				if(num > 32)
	    					return "ERROR";
	    				double d_ = d * 2;
	    				int x = (int)d_;
	    				sb.append(x);
	    				d = d_ - x;
	    			}
	    			return sb.toString();
	    		}
	    		
	    	}

	    	return "ERROR";
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值