Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d301711

Browse files
166. Fraction to Recurring Decimal (java)
1 parent 4492ccc commit d301711

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public String fractionToDecimal(int numerator, int denominator) {
3+
boolean minus = numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0;
4+
HashMap<Long, Integer> remains = new HashMap<>(16);
5+
List<Long> resList = new ArrayList<>();
6+
long n;
7+
if(numerator > 0) n = numerator;
8+
else if(numerator > Integer.MIN_VALUE) n = -numerator;
9+
else n = Integer.MAX_VALUE + 1L;
10+
long d;
11+
if(denominator > 0) d = denominator;
12+
else if(denominator > Integer.MIN_VALUE) d = -denominator;
13+
else d = Integer.MAX_VALUE + 1L;
14+
long r = n % d;
15+
int index = 0 , loopPos = -1;
16+
while(r != 0){
17+
if(remains.containsKey(r)){
18+
loopPos = remains.get(r);
19+
break;
20+
}
21+
remains.put(r, ++index);
22+
resList.add(Math.abs(n / d));
23+
n = r;
24+
n *= 10;
25+
r = n % d;
26+
}
27+
resList.add(Math.abs(n / d));
28+
StringBuilder res = new StringBuilder();
29+
if(minus) res.append("-");
30+
for(int i = 0; i < resList.size(); i++){
31+
if(i == 1) res.append(".");
32+
if(loopPos == i) res.append("(");
33+
res.append(resList.get(i));
34+
}
35+
if(loopPos != -1) res.append(")");
36+
return res.toString();
37+
}
38+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /