[Leetcode] Fraction to recurring Decimal

Source: Internet
Author: User

Title Description:

Fraction to recurring Decimal

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) ".

Problem Solving Ideas:

1. To find out the sequence of the repeating decimal, we need to find the same remainder, then the 2 decimal numbers calculated by the same remainder are repeating decimal;

2. Because of the need to insert parentheses between the Loop series, the hash table is used to record the position of the corresponding result in the case of the remainder.

3. The data of this topic is larger, the use of int type is not enough, need to use int64_t type.

Problem Solving Code:

classSolution { Public:    stringFractiontodecimal (int64_t numerator, int64_t denominator) {stringresult =""; if(Numerator * Denominator <0) {result+='-'; } int64_t num= ABS (numerator), den =ABS (denominator); Result+ = to_string (num/den); if(num% den = =0)        {            returnresult; }        Else{result+='.'; } int64_t rem= num%den; Map<int,int>Rem_map;  while(REM! =0)        {            if(Rem_map[rem] >0) {Result.insert (Rem_map[rem],1,'('); Result+=')';  Break; } Rem_map[rem]=result.size (); REM*=Ten; Result+ = to_string (REM/den); REM%=den; }                returnresult; }};

[Leetcode] 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.