18
18
class FractionToRecurringDeci {
19
19
20
20
public static void main (String [] args ) {
21
- // System.out.println(fractionToDecimal(1, 2));
22
- // System.out.println(fractionToDecimal(2, 1));
23
- // System.out.println(fractionToDecimal(2, 3));
24
- System .out .println (fractionToDecimal (Integer .MAX_VALUE , Integer .MIN_VALUE ));
21
+ FractionToRecurringDeci f = new FractionToRecurringDeci ();
22
+ // System.out.println(f.fractionToDecimal(1, 2));
23
+ // System.out.println(f.fractionToDecimal(2, 1));
24
+ // System.out.println(f.fractionToDecimal(2, 3));
25
+ System .out .println (f .fractionToDecimal (Integer .MAX_VALUE , Integer .MIN_VALUE ));
25
26
}
26
27
27
28
/**
@@ -32,34 +33,33 @@ public static void main(String[] args) {
32
33
* After dot = remainder * 10 / denominator
33
34
* if already showed up, insert parentheses
34
35
*/
35
- public static String fractionToDecimal (int numerator , int denominator ) {
36
+ public String fractionToDecimal (int numerator , int denominator ) {
36
37
if (denominator == 0 ) return "" ;
37
38
if (numerator == 0 ) return "0" ;
38
39
39
40
StringBuilder res = new StringBuilder ();
40
- Long n = new Long (numerator );
41
+ Long n = new Long (numerator ); // convert to long
41
42
Long d = new Long (denominator );
42
- if (n * d < 0 ) res .append ("-" );
43
+ if (( n < 0 && d > 0 ) || ( n > 0 && d < 0 )) res .append ("-" ); // negative
43
44
44
- n = Math .abs (n );
45
+ n = Math .abs (n ); // to abstract value
45
46
d = Math .abs (d );
46
- res .append (n / d );
47
- if (n % d == 0 ) return res .toString ();
47
+ res .append (n / d ); // before dot
48
+ if (n % d == 0 ) return res .toString (); // no fraction
48
49
49
- res .append ("." );
50
- // use map to remember the index of same remainder
51
- Map <Long , Integer > map = new HashMap <Long , Integer >();
52
- Long r = n % d ;
50
+ res .append ("." ); // add dot
51
+ HashMap <Long , Integer > map = new HashMap <Long , Integer >();
52
+ Long r = n % d ; // get first remainder
53
53
while (r > 0 ) {
54
- if (map .containsKey (r )) {
55
- res .insert (map .get (r ), "(" );
56
- res .append (")" );
54
+ if (map .containsKey (r )) { // remainder appeared before
55
+ res .insert (map .get (r ), "(" ); // insert an open paren
56
+ res .append (")" ); // append a close paren
57
57
break ;
58
58
}
59
- map .put (r , res .length ());
60
- r *= 10 ; // remainder * 10 / denominator
59
+ map .put (r , res .length ()); // save remainder and the length
60
+ r *= 10 ; // simulate long division
61
61
res .append (r / d );
62
- r %= d ; // get remainder
62
+ r %= d ; // get next remainder
63
63
}
64
64
return res .toString ();
65
65
}
0 commit comments