-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetCode_166.java
More file actions
50 lines (34 loc) · 1.27 KB
/
Copy pathleetCode_166.java
File metadata and controls
50 lines (34 loc) · 1.27 KB
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
class Solution {
public String fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) {
return "0";
}
String result= "";
result = (((numerator > 0) ^ (denominator > 0)) ? "-" : "").concat(result);
long num = Math.abs((long)numerator);
long den = Math.abs((long)denominator);
if(num % den == 0){
return result.concat(String.valueOf(num/den));
}
HashMap<Long, Integer> map = new HashMap<>();
long q = num/den;
long r = num % den;
result = result.concat(String.valueOf(q));
result = result.concat(".");
map.put(r, result.length());
while(r != 0){
r *= 10;
q = r/den;
r = r % den;
result = result.concat(String.valueOf(q));
if(map.get(r) == null){
map.put(r, result.length());
}else{
int post = map.get(r);
result = result.substring(0, post) + '(' + result.substring(post, result.length()) + ')';
break;
}
}
return result;
}
}