1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public String printBin(double num) { StringBuilder sb = new StringBuilder("0."); while (sb.length() <= 32 && num != 0) { num *= 2; int digit = (int) num; sb.append(digit); num -= digit; } return sb.length() <= 32 ? sb.toString() : "ERROR"; } }
|
注意该题是输出二进制数,而不是 Double 对应的二进制表示。示例 0.625 = 5/8 = 0.101。
References
面试题 05.02. 二进制数转字符串