Given integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part was repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0. (6) ".
Problem Solving Ideas:
A variety of critical values will appear in the test, so you need to convert numerator and denominator to long, and then calculate the integer part, and for the fractional part, the post-processing will be numerator*10, on the one hand, the calculated value is placed in a list, On the other hand, the new molecule is placed in the map, because the new molecule is certainly smaller than denominator, so there will be 0 or repeat (so the score is either finite, or infinite loop decimal) Once the new denominator repeats, meaning that the result will appear a cyclic value, it can be written according to the rules, The Java implementation is as follows:
Public String fractiontodecimal (int numerator, int denominator) {StringBuilder sb = new StringBuilder (); if (numerator < 0 && denominator > 0) sb.append ("-"), else if (Numerator > 0 && Denominator < 0) sb.append ("-") ; Long Lnumerator = (long) numerator;if (Lnumerator < 0) Lnumerator =-lnumerator; Long Ldenominator = (long) denominator;if (Ldenominator < 0) Ldenominator =-ldenominator;if (lnumerator% Ldenominator = = 0) {sb.append (lnumerator/ldenominator); return sb.tostring ();} Sb.append (Lnumerator/ldenominator + "."); System.out.println (Lnumerator); Lnumerator%= Ldenominator; System.out.println (Lnumerator); Hashmap<long, integer> map = new Hashmap<long, integer> (); arraylist<integer> list = new arraylist<integer> () map.put (lnumerator, 0); while (true) {Lnumerator *= 10; while (Lnumerator < Ldenominator) {list.add (0); Map.put (Lnumerator, List.size ()); Lnumerator *= 10;} List.add ((int) (lnumerator/ldenominator)); Lnumerator%= LdenominAtor;if (Lnumerator = = 0) {for (int i = 0; i < list.size (); i++) Sb.append (List.get (i)); return sb.tostring ();} else if ( Map.containskey (Lnumerator)) {for (int i = 0; i < Map.get (lnumerator); i++) Sb.append (List.get (i)), Sb.append ("("); for (int i = Map.get (lnumerator); I < list.size (); i++) Sb.append (List.get (i)); Sb.append (")"); return sb.tostring ();} Map.put (Lnumerator, List.size ());} }
Java for Leetcode 166 fraction to recurring Decimal