Fraction to recurring Decimal

Source: Internet
Author: User

Ideas: 1, the molecular 0 can be returned in advance

2, the result is positive and negative judgment

3. Array out of bounds (minimum negative number divided by -1)

4, for the beginning of the encounter decimal to add ".", there is a decimal can expand dividend, for whether there is a repetition of the place to judge whether its dividend is repeated!!!

For the ABS () function, remember to convert the number to a long integer, and then use ABS (), otherwise the minimum negative numbers are not converted positive!!!

classSolution { Public:    stringFractiontodecimal (intNumerator,intdenominator) {        stringRes; if(numerator==0)return "0"; if((numerator<0) ^ (denominator<0)) Res+="-"; Long Longn=numerator; Long LongD=denominator; N=ABS (n); D=ABS (d); Unordered_map<int,int>Rep; BOOLisfract=false;  while(true)        {            if(n<d) {if(isfract==false)                {                    if(res==""|| res=="-") Res+="0."; ElseRes+="."; Isfract=true; } N*=Ten; }            intr=n-n/d*D; if(r==0) {res+=to_string (n/d); returnRes; }            Else            {                if(isfract==true)                {                    if(Rep.find (n) = =Rep.end ()) {Res+=to_string (n/d); Rep[n]=res.size ()-1; }                     Else                     {                         intpos=Rep[n]; Res=RES.SUBSTR (0, POS) +"("+RES.SUBSTR (POS) +")"; returnRes; }                }                ElseRes+=to_string (n/d); N=R; }                    }    }};

Fraction to recurring Decimal

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.