-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathFractiontoRecurringDecimal.java
More file actions
34 lines (34 loc) · 1.11 KB
/
FractiontoRecurringDecimal.java
File metadata and controls
34 lines (34 loc) · 1.11 KB
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
public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
StringBuilder res = new StringBuilder();
boolean isPositive = numerator > 0 && denominator > 0 || numerator < 0 && denominator < 0;
if (!isPositive)
res.append('-');
long n = Math.abs((long) numerator);
long d = Math.abs((long) denominator);
res.append(n / d);
long remain = n % d;
if (remain == 0) {
return res.toString();
}
res.append('.');
Map<Long, Integer> numToPosition = new HashMap<>();
numToPosition.put(remain, res.length());
while (remain > 0) {
remain *= 10;
res.append(remain / d);
remain %= d;
if (numToPosition.containsKey(remain)) {
res.insert(numToPosition.get(remain), "(");
res.append(")");
break;
} else {
numToPosition.put(remain, res.length());
}
}
return res.toString();
}
}