标签:style blog color os io ar div log new
思路:依次减去 0.5,0.25,0.125。。。 够减二进制为1,不够减二进制为0。
public class Solution { public static String printBinary(double num) { if (num >= 1 || num <= 0) return "ERROR"; StringBuilder res = new StringBuilder(); res.append(‘.‘); double frac = 0.5; while (num > 0) { if (res.length() >= 32) return "ERROR"; if (num >= frac) { res.append(1); num -= frac; } else { res.append(0); } frac /= 2; } return res.toString(); } public static void main(String[] args) { System.out.println(printBinary(0.875)); } }
标签:style blog color os io ar div log new
原文地址:http://www.cnblogs.com/jdflyfly/p/3931372.html