思路:依次减去 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)); } }
时间: 2024-10-10 05:22:27