友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
166. Fraction to Recurring Decimal
需要注意的是是:在 Map 中放的是被除数,而不是计算出来的位数digit。这样更方便处理!
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
Example 1:
Input: numerator = 1, denominator = 2 Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1 Output: "2"
Example 3:
Input: numerator = 2, denominator = 3 Output: "0.(6)"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Runtime: 1 ms, faster than 100.00% of Java online submissions for Fraction to Recurring Decimal.
*
* Memory Usage: 34.8 MB, less than 100.00% of Java online submissions for Fraction to Recurring Decimal.
*
* Copy from: https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/51106/My-clean-Java-solution[My clean Java solution - LeetCode Discuss]
*/
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
StringBuilder result = new StringBuilder();
result.append(numerator > 0 ^ denominator > 0 ? "-" : "");
long num = Math.abs((long) numerator);
long den = Math.abs((long) denominator);
if (num > den) {
result.append(num / den);
} else {
result.append("0");
}
num %= den;
if (num == 0) {
return result.toString();
}
result.append(".");
Map<Long, Integer> numToIndexMap = new HashMap<>();
// 这里需要注意,在 Map 中放的是被除数,而不是计算出来的位数digit。
numToIndexMap.put(num, result.length());
while (num != 0) {
num *= 10;
result.append(num / den);
num %= den;
if (numToIndexMap.containsKey(num)) {
Integer index = numToIndexMap.get(num);
result.insert(index, "(");
result.append(")");
break;
} else {
numToIndexMap.put(num, result.length());
}
}
return result.toString();
}