Leetcode 166. Fraction to recurring Decimal

Source: Internet
Author: User

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

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.