Sunday, October 21, 2012

BitManipulation4

Q4. Given a (decimal - e.g. 21.125) number N that is passed in as a string, print the binary representation (as a string). If the number cannot be represented accurately in binary, print "ERROR".
  • Take care of all edge cases.
  • Output only 4 significant binary digits after decimal
[This question was asked in Amazon online programming test]

Answer:

public class BitManipulation4 {
    static String decimalToBinary(String a) {
        if (a == null) {
            return "ERROR";
        }

        String[] number = a.split("\\.");
        if (number.length > 2) {
            return "ERROR";
        }

        int decimal = Integer.parseInt(number[0]);
        int fractional = 0;
        if (number.length == 2) {
            fractional = Integer.parseInt(number[1]);
        }

        String binary = Integer.toBinaryString(decimal);
        binary += ".";

        double d = Double.parseDouble("." + fractional);
        for (int i = 1; i <= 4; i++) {
            String t = ((int) 2 * d) >= 1 ? "1" : "0";
            binary += t;
            d = 2 * d;
            if (d >= 1) {
                d -= 1;
            }
        }
        return binary;
    }

    public static void main(String[] args) {
        System.out.println(decimalToBinary("23.2"));
        System.out.println(decimalToBinary("6.25"));
        System.out.println(decimalToBinary("23.2.3"));
        System.out.println(decimalToBinary(null));
        System.out.println(decimalToBinary("15"));
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.