-
Notifications
You must be signed in to change notification settings - Fork 1
/
166. Fraction to Recurring Decimal.java
54 lines (42 loc) · 1.15 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if(numerator==0)
{
return "0";
}
StringBuilder sb = new StringBuilder();
if ((numerator < 0) ^ (denominator < 0)) {
sb.append("-");
}
long num = Math.abs((long)numerator);
long den = Math.abs((long)denominator);
sb.append(num / den);
num = num % den;
if(num==0)
{
return sb.toString();
}
sb.append(".");
//map to keep track of repeating decimal pattern
HashMap<Long,Integer> map = new HashMap<>();
map.put(num, sb.length());
while(num!=0)
{
num = num*10;
sb.append(num/den);
num = num % den;
if(map.containsKey(num))
{
int index = map.get(num);
sb.insert(index, "(");
sb.append(")");
break;
}
else
{
map.put(num, sb.length());
}
}
return sb.toString();
}
}