forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
166_fractionToDecimal.java
33 lines (28 loc) · 1.02 KB
/
166_fractionToDecimal.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
public class Solution {
public String fractionToDecimal(int numerator, int denominator) {
StringBuffer sb = new StringBuffer();
if((numerator > 0 && denominator <0) || (numerator < 0 && denominator >0))sb.append("-");
long num = Math.abs((long)numerator);
long den = Math.abs((long)denominator);
sb.append(num/den);
if(num%den == 0) return sb.toString();
sb.append("."); // dont forget!!!
num %= den;
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
map.put(num, sb.length());
while(num!=0){
num*=10; //dont forget!!!
sb.append(num/den);
num%=den;
if(map.containsKey(num)){
int index = map.get(num);
sb.insert(index, "(");
sb.append(")");
return sb.toString();
} else{
map.put(num, sb.length());
}
}
return sb.toString();
}
}