Binary Representation 180

Question

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".

Solution

将数字分为整数和小数两部分解决。根据“.”将n拆成两部分,注意"."是转义字符,需要表示成"\.",而不能直接用"."。corner case: n中没有"."。

整数部分:除以2取余数直到除数为0为止,转换成二进制数。corner case: "0"或者""的情况(之前n可能是"0.x"或者".x"),直接返回"0"。

小数部分:乘以2取整数部分直到小数部分为0或者出现循环为止,转换成二进制数。corner case: "0"或者""的情况(之前n可能是"x.0"或者"x."),直接返回"0"。用一个set记录数否出现重复的数,当出现重复的数或者当超过一定位数(这里取32)还不能完全表示小数部分时,返回"ERROR"。

代码如下:

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
        if(n == null || n.length() == 0){
            return "0";
        }

        if(n.indexOf('.') == -1){
            return parseInteger(n);
        }

        String[] num = n.split("\\.");
        String f = parseFloat(num[1]);
        if(f.equals("ERROR")){
            return "ERROR";
        }

        if(f.equals("") || f.equals("0")){
            return parseInteger(num[0]);
        }

        return parseInteger(num[0]) + "." + f;
    }

    private String parseInteger(String s){
        int d = Integer.parseInt(s);
        if(s.equals("") || s.equals("0")){
            return "0";
        }
        String res = "";
        while(d != 0){
            res = Integer.toString(d % 2) + res;
            d /= 2;
        }
        return res;
    }

    private String parseFloat(String s){
        double d = Double.parseDouble("0." + s);
        if(s.equals("") || s.equals("0")){
            return "0";
        }
        String res = "";
        HashSet<Double> set = new HashSet<Double>();
        while(d != 0){
            //出现循环
            if(res.length() > 32 || set.contains(d)){
                return "ERROR";
            }
            set.add(d);
            d = d * 2;
            if(d >= 1){
                res += "1";
                d = d - 1;
            }else{
                res += "0";
            }
        }
        return res;
    }
}

results matching ""

    No results matching ""