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) ".
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
1 Public classSolution {2 PublicString Fractiontodecimal (intNumerator,intdenominator) {3 if(numerator==0) {4 return"0";5 }6String result= "";7 if(numerator<0 ^ denominator<0) {8result+= "-";9 }Ten Longn=numerator; One LongD=denominator; An=Math.Abs (n); -D=Math.Abs (d); - Longr=n%D; theresult+=n/D; - if(r==0) { - returnresult; -}Else { +result+= "."; - } +Hashmap<long, integer> map=NewHashmap<>(); A while(r>0) { at if(Map.containskey (R)) { - -Result=result.substring (0, Map.get (r)) + "(" +result.substring (Map.get (R) + ")"; - returnresult; -}Else { - Map.put (R, Result.length ()); inr*=10; -result+=r/D; tor=r%D; + } - } the returnresult; * } $}
Leetcode Fraction to recurring Decimal