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) ".
Analyse:use Hash to store the fractional and its corresponding position at result. If The fractional has occurred, the result is recurring; If The fractional is 0, return to current result.
Runtime:0ms.
1 classSolution {2 Public:3 stringFractiontodecimal (intNumerator,intdenominator) {4 if(!numerator)return "0";5 6 stringresult;7unordered_map<int,int>um;8 if(Numerator <0^ Denominator <0) Result + ='-';9 Long Long intNu = numerator, de =denominator;TenNu =abs (NU); OneDe =abs (DE); A -Result + = To_string (Nu/de); - Long Long intFractional = nu%de; the if(!fractional)returnresult; -Result + ="."; - - while(fractional) { + //find if the fractional is in UM - if(Um.find (fractional)! =Um.end ()) { +Result.insert (Um[fractional],"("); AResult + =")"; at returnresult; - } - - //Push the fractional and its position in result into UM -Um[fractional] =result.length (); - inFractional *=Ten; -Result + = to_string (Fractional/de); toFractional%=de; + } - returnresult; the } *};
Fraction to recurring Decimal