-
Notifications
You must be signed in to change notification settings - Fork 0
/
166. Fraction to Recurring Decimal.java
40 lines (33 loc) · 1.3 KB
/
166. Fraction to Recurring Decimal.java
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
// 166. Fraction to Recurring Decimal
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0 || denominator == 0) {
return "0";
}
StringBuilder sb = new StringBuilder();
if (numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0) { // to find number is negative or bot
sb.append("-");
}
long num = Math.abs((long) numerator);
long denom = Math.abs((long) denominator);
long remainder = num % denom;
sb.append(num/denom);
if (remainder == 0) {
return sb.toString();
}
sb.append(".");
Map<Long, Integer> map = new HashMap<>();
while (remainder != 0) {
if (map.containsKey(remainder)) { // once you see the same remainder then you know it's going to start recurring
sb.insert(map.get(remainder), "(");
sb.append(")");
break;
}
map.put(remainder, sb.length());
remainder *= 10;
sb.append(remainder/denom);
remainder = remainder % denom;
}
return sb.toString();
}
}