Fraction to recurring Decimal

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.