/* Binary to String: Given a real number between 0 and 1 (e.g., 0.72) that is passed in as a double, print the binary representation. If the number cannot be represented accurately in binary with at most 32 characters, print"ERROR:' */ public class Main { public static void main(String[] args) { System.out.println("Hello World!"); double n = 0.625; printBin(n); } public static void printBin(double n) { if(n <= 0 || n >= 1) { System.out.println("ERROR"); return; } StringBuilder sb = new StringBuilder(); sb.append("."); while(n > 0) { if(sb.length() >= 32) { System.out.println("ERROR"); return; } if(n * 2 >= 1) { sb.append("1"); n = n * 2 - 1; } else { sb.append("0"); n = n * 2; } } System.out.println(sb.toString()); } }
Binary to String java 走地牙 CTCI 5.2
最新推荐文章于 2021-03-13 11:27:10 发布