-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfraction-to-recurring-decimal.java
45 lines (35 loc) · 1.23 KB
/
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
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
//take care of num 0
if(numerator==0)
return "0";
StringBuilder fraction = new StringBuilder();
//take care of -ve sign
if(numerator<0 ^ denominator <0)
fraction.append("-");
//take care of overflow
long dividend = Math.abs((long)(numerator));
long divisor = Math.abs((long)(denominator));
fraction.append(String.valueOf(dividend/divisor));
long rem=dividend % divisor;
//whole results
if(rem == 0)
return fraction.toString();
fraction.append(".");
HashMap<Long,Integer> map = new HashMap<Long,Integer>();
while(rem!=0)
{
if(map.containsKey(rem))
{
fraction.insert(map.get(rem),"(");
fraction.append(")");
break;
}
map.put(rem,fraction.length());
rem*=10;
fraction.append(String.valueOf(rem/divisor));
rem%=divisor;
}
return fraction.toString();
}
}