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
+ public class Solution {
21
+ public String fractionToDecimal (int numerator ,int denominator ) {
22
+ if (numerator ==0 )return new String ("0" );
23
+ boolean flag = (numerator <0 )^(denominator <0 );
24
+ long Numerator =Math .abs ((long )numerator );
25
+ long Denominator =Math .abs ((long )denominator );
26
+ StringBuffer res =new StringBuffer ();
27
+ if (flag ==true )res .append ('-' );
28
+ res .append (String .valueOf ((Numerator /Denominator )));
29
+ Numerator =Numerator %Denominator ;
30
+ if (Numerator ==0 )return res .toString ();
31
+ res .append ('.' );
32
+ HashMap <Long ,Integer >map =new HashMap <Long ,Integer >();
33
+ for (int i =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 )return res .toString ();
42
+ res .insert (map .get (Numerator ),"(" );
43
+ res .append (')' );
44
+ return res .toString ();
45
+ }
46
+ }