题目链接:https://leetcode.cn/problems/bianry-number-to-string-lcci/
# 法一
直接模拟计算,直到超出,具体看源码
class Solution { | |
public String printBin(double num) { | |
char[] chs = String.valueOf(num).toCharArray(); | |
int n = chs.length; | |
// 题目保证最后只有 6 位小数,因此最多循环 10 次 | |
final int N = 10; | |
// 被减数 | |
int a; | |
// 减数 | |
int b = 5; | |
// 余数 | |
int d = 0; | |
StringBuilder sb = new StringBuilder("0."); | |
for (int i = 0; i < N; ++i) { | |
a = d * 10 + (i + 2 < n ? chs[i + 2] - '0' : 0); | |
if (a >= b) { | |
sb.append(1); | |
d = a - b; | |
if (a == b && i + 2 == n - 1) break; | |
} else { | |
sb.append(0); | |
d = a; | |
} | |
b *= 5; | |
} | |
return d == 0 ? sb.toString() : "ERROR"; | |
} | |
} |
# 提交结果
# 法二
# 解题思路
总结归纳:一直乘以 2,直到变成 1,或者无线循环下去;因为题目要求,故仅需要循环 30 次即可。
# 提交结果
# 源码
class Solution { | |
public String printBin(double num) { | |
StringBuilder res = new StringBuilder("0."); | |
while (res.length() <= 32 && num != 0) { | |
num *= 2; | |
if (num >= 1) { | |
res.append(1); | |
num -= 1; | |
} else { | |
res.append(0); | |
} | |
} | |
return res.length() > 32 && num != 0 ? "ERROR" : res.toString(); | |
} | |
} |