The result is a loop after the decimal point, with parentheses enclosing the part of the loop that appears.
Find out the loop part of the idea:
Maintains a unordered_map<long, long>dict, corresponding relationship is the remainder and its position in the Res. Each time a decimal point is computed, the lookup is already in dict, and if it is already there, the duplicate part has been found (such as result 0. (012), the current get res= "0.012", the result is again obtained 0, so the decimal point after the first 0 start part 012 is the loop part), then insert parentheses in Res return res.
The idea of division:
Remain stores the remainder of each division, while (remain) loop, each remain *= in the loop, res + = Remain/denominator, remain = remain% denominator.
1 classSolution {2 Public:3 stringFractiontodecimal (intNumerator,intdenominator) {4 if(!numerator)return "0";5 stringres ="";6 if(Numerator <0^ Denominator <0) Res + ="-";7 Longm = ABS (Long(numerator));8 Longn = ABS (Long(denominator));9 Longs = m/N;TenRes + =to_string (s); One A Longremain = m%N; - if(!remain)returnRes; -Res + ="."; the -unordered_map<Long,Long>dict; - - while(remain) { + if(Dict.find (remain)! =Dict.end ()) { -Res.insert (Dict[remain],"("); +Res + =")"; A returnRes; at } -Dict[remain] =res.length (); -Remain *=Ten; -s = remain/N; -Res + =to_string (s); -remain = remain%N; in } - returnRes; to } +};
Pay attention to determine the RES sign part, use the XOR ^.
Leetcode 166. Fraction to recurring Decimal