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) ".
Hint:
- No scary Math, just apply elementary math knowledge. Still remember how to perform a long division?
- Try a long division on 4/9, and the repeating part is obvious. Now try 4/333. Do you see a pattern?
- Be wary of Edge cases! List out as many test cases as can think of and test your code thoroughly.
Public classSolution { PublicString Fractiontodecimal (intNumerator,intdenominator) { if(Numerator = = 0) { return"0"; } StringBuilder Res=NewStringBuilder (); //"+" or "-"Res.append (((Numerator > 0) ^ (Denominator > 0))? "-" : ""); Longnum = Math.Abs (Long) numerator); LongDen = Math.Abs ((Long) denominator); //Integral partRes.append (num/den); Num%=den; if(num = = 0) { returnres.tostring (); } //Fractional partRes.append ("."); HashMap<long, integer> map =NewHashmap<long, integer>(); Map.put (num, res.length ()); while(num! = 0) {num*= 10; Res.append (Num/den); Num%=den; if(Map.containskey (num)) {intindex =map.get (num); Res.insert (Index,"("); Res.append (")"); Break; } Else{map.put (num, res.length ()); } } returnres.tostring (); }}
166. Fraction to recurring Decimal