Notes:
1. When numerator is 0, return "0". Check This corner case, because 0/-5 would return-0.
2. Use a long long int for DIVD and divs, mainly for divs. Because when divs = Int_min, Fabs (divs) is large.
3. Forget to rest *= to get the next level.
1 classSolution {2 Public:3 stringFractiontodecimal (intNumerator,intdenominator) {4 if(Numerator = =0)return "0";5 stringresult;6 if(Numerator <0^ Denominator <0) result ="-";7 Long Long intDIVD = Fabs (numerator), divs = Fabs (denominator), rest = divd%divs;8Result + = To_string (DIVD/divs);9 if(Rest = =0) {Ten returnresult; One } AResult + ='.'; -unordered_map<int,int>mapping; - while(Rest >0) { the if(Mapping.find (rest)! =Mapping.end ()) { -Result.insert (Mapping[rest],"("); -Result + =')'; - returnresult; + } -Mapping[rest] =result.size (); +Rest *=Ten; AResult + = To_string (rest/divs); atRest%=divs; - } - returnresult; - } -};
Leetcode–refresh–fraction to recurring Decimal