-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet-code-q-30.java
More file actions
32 lines (27 loc) · 903 Bytes
/
leet-code-q-30.java
File metadata and controls
32 lines (27 loc) · 903 Bytes
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
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) return "0";
StringBuilder res = new StringBuilder();
if ((numerator < 0) ^ (denominator < 0)) res.append('-');
long n = Math.abs((long) numerator);
long d = Math.abs((long) denominator);
res.append(n / d);
long rem = n % d;
if (rem == 0) return res.toString();
res.append('.');
Map<Long, Integer> seen = new HashMap<>();
while (rem != 0) {
if (seen.containsKey(rem)) {
int pos = seen.get(rem);
res.insert(pos, "(");
res.append(')');
break;
}
seen.put(rem, res.length());
rem *= 10;
res.append(rem / d);
rem = rem % d;
}
return res.toString();
}
}