Fraction to recurring DecimalTotal Accepted:
3168 Total Submissions:
27432
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) ".
Analysis
The key is to determine where the loop takes place, using the map to store all the remainder, and a loop occurs when the remainder is already obsolete.
Note
Overflow, the processing of symbols, separate two functions, make the code easier to read
[CODE]
public class Solution {public String fractiontodecimal (int numerator, int denominator) {Long num = num Erator; Long den = denominator; Boolean neg = num * den < 0; num = Math.Abs (num); Den = Math.Abs (DEN); String res = neg? "-" + long.tostring (Num/den): long.tostring (Num/den); long remainder = Num%den; Return (remainder==0)? Res: (res + "." + getdec (remainder, den)); } private StringBuilder Getdec (long remainder, long den) {map<long, integer> Map = new Hashmap<lon G, integer> (); int i=0; StringBuilder sb = new StringBuilder (); while (remainder!=0 &&!map.containskey (remainder)) {map.put (remainder, i); ++i; Remainder *= 10; Sb.append (long.tostring (Remainder/den)); Remainder%= den; } if (remainder!=0) {Sb.insert ((int) map.get (remainder), ' ('); Sb.append (') '); } return SB; }}
Leetcode 166:fraction to recurring Decimal