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) "
The solution to this problem is to simulate the process of division, and then use HashMap to store the remainder of each step, and the current length of the output to be obtained.
It is important to note that in extreme cases, such as the smallest negative int, when converted to a positive number, it overflows int, so a long value is required to handle the input value.
In addition, the Insert method has to be noted.
Public classSolution { PublicString Fractiontodecimal (intNumerator,intdenominator) { if(numerator==0){ return"0"; } Longnum = Math.Abs (Long) numerator); LongDen = Math.Abs ((Long) denominator); StringBuilder Res=NewStringBuilder (); HashMap<long, integer> container =NewHashMap (); BooleanIsnegative=false; if(Numerator < 0) {isnegative= !isnegative; } if(denominator<0) {isnegative= !isnegative; } if(isnegative) {res.append (‘-‘); } LongReminder = num%den; Res.append (Num/den); intSize =res.length (); BooleanHascycle =false; while(Reminder! = 0 ){ if(Container.isempty ()) {Res.append (‘.‘); Size++; } if(!Container.containskey (Reminder)) {Size++; LongNewquoient = reminder*10/den; Res.append (newquoient); Container.put (reminder,size); Reminder= reminder*10%den; } Else{hascycle=true; Break; } } if(!hascycle) { returnres.tostring (); } Else{Res.insert (Container.get (reminder)-1, "("); Res.append (‘)‘); returnres.tostring (); } }}
Leetcode-fraction to recurring Decimal