?
Package cn.edu.xidian.sselab.hashtable;
Import Java.util.HashMap; Import Java.util.Map;
/** * * @author Zhiyong Wang * Title:fraction to recurring Decimal * Content: * 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) ". * * */ public class Fractiontorecurringdecimal {
I cannot solve this problem by myself The first thing to consider is the special case (1) numerator is 0 (2) denominator is 0 (3) Positive negative problem And then because the string is returned, and the result is a patchwork result, we use the StringBuilder append method to cobble together the results. The first step is to take the sign (in an XOR way to obtain the sign), (note that before starting, the two number is to take the absolute value operation) and then the integer part, then a one after adding the remainder *10, divided by the result of the denominator The remainder is saved with HashMap, with the length of the result, and the remainder is used to determine when the loop begins, and the length is used to record the starting position of the parentheses added. Public String fractiontodecimal (int numerator, int denominator) { if (numerator = = 0) return "0"; if (denominator = = 0) return null; StringBuilder strb = new StringBuilder (); "+" or "-" Strb.append (((numerator>0) ^ (denominator>0))? " -":""); Long num = Math.Abs ((long) numerator); Long den = Math.Abs ((long) denominator); Integral part Strb.append (Num/den); Num%= den; if (num = = 0) return strb.tostring (); Fractional part Strb.append ("."); Map map = new HashMap (); while (num! = 0) { if (!map.containskey (num)) { Map.put (num, strb.length ()); Num *= 10; Strb.append (Num/den); Num%= den; }else{ int index = (int) map.get (num); Strb.insert (Index, "("); Strb.append (")"); Break }
} return strb.tostring (); } }
|
Fraction to recurring Decimal