Movatterモバイル変換


[0]ホーム

URL:


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

Commitf6b2eea

Browse files
author
applewjg
committed
Fraction to Recurring Decimal
1 parent379026b commitf6b2eea

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎FractionToRecurringDecimal.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Dec 15, 2014
4+
Problem: Fraction to Recurring Decimal
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/fraction-to-recurring-decimal/
7+
Notes:
8+
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
9+
10+
If the fractional part is repeating, enclose the repeating part in parentheses.
11+
12+
For example,
13+
14+
Given numerator = 1, denominator = 2, return "0.5".
15+
Given numerator = 2, denominator = 1, return "2".
16+
Given numerator = 2, denominator = 3, return "0.(6)".
17+
18+
Solution: ...
19+
*/
20+
publicclassSolution {
21+
publicStringfractionToDecimal(intnumerator,intdenominator) {
22+
if (numerator ==0)returnnewString("0");
23+
booleanflag = (numerator <0)^(denominator <0);
24+
longNumerator =Math.abs((long)numerator);
25+
longDenominator =Math.abs((long)denominator);
26+
StringBufferres =newStringBuffer();
27+
if (flag ==true)res.append('-');
28+
res.append(String.valueOf((Numerator /Denominator)));
29+
Numerator =Numerator %Denominator;
30+
if (Numerator ==0)returnres.toString();
31+
res.append('.');
32+
HashMap<Long,Integer>map =newHashMap<Long,Integer>();
33+
for (inti =res.length();Numerator !=0; ++i) {
34+
if (map.get(Numerator) !=null)break;
35+
map.put(Numerator,i);
36+
Numerator *=10;
37+
res.append(String.valueOf((Numerator /Denominator)));
38+
Numerator %=Denominator;
39+
}
40+
41+
if (Numerator ==0)returnres.toString();
42+
res.insert(map.get(Numerator),"(");
43+
res.append(')');
44+
returnres.toString();
45+
}
46+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp