https://leetcode-cn.com/problems/fraction-to-recurring-decimal/
![](https://img.haomeiwen.com/i1560080/c3f81a6d5b877389.png)
(图片来源https://leetcode-cn.com/problems/fraction-to-recurring-decimal/
)
日期 | 是否一次通过 | comment |
---|---|---|
2020-03-18 | 0 | |
2020-03-18 | 0 |
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
StringBuilder res = new StringBuilder();
/** 异或判断符号,只要分子分母不同则为负 */
res.append(((numerator > 0) ^ (denominator > 0)) ? "-" : "");
long num = Math.abs((long) numerator);
long den = Math.abs((long) denominator); // 不转为long,则可能溢出
/** 整数部分 */
res.append(num / den);
num %= den;
if (num == 0) {
return res.toString();
}
/** 小数部分 */
res.append(".");
HashMap<Long, Integer> map = new HashMap<>(); // 存放数字出现的位置
map.put(num, res.length());
while (num != 0) {
num *= 10;
res.append(num / den);
num %= den;
if (map.containsKey(num)) {
int index = map.get(num);
res.insert(index, "(");
res.append(")");
break;
} else {
map.put(num, res.length());
}
}
return res.toString();
}
网友评论