[C + +] leetcode:82 Fraction to recurring Decimal

Source: Internet
Author: User
Tags string format time 0

Topic:

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

Test instructions: given a numerator and a denominator, returns the decimal in the form of a string. If the decimal infinite loop, enclose the loop body with parentheses.

idea: Handwritten computing division method

    0.16  6) 1.00       1 0       <--remainder=1, Mark 1 as seen at position=0.    -      <--remainder=4, Mark 4 as seen at Position=1.    -       4      <--remainder=4 was seen before at Position=1, so the fractional part which is starts REPEA Ting at position=1 = 1 (6).

The key point is how to determine the loop body?

We use a hashmap to record each remainder, and the position where the remainder occurs, and when there is a repetition of the remainder, the division begins to enter the loop, and the part between the two repeating remainder is the loop body.

Example : 1/13=0. 076923 076923 076923 ..., when the decimal part appears for the second time 0 o'clock, which means that the loop is started, you need to enclose 076923 in parentheses, and the result is 0. (076923).

Attention:

1. Structure of the HashMap

Hashmap<key, value> respectively corresponds to the current remainder of the <, corresponding to the result subscript (position) >. This allows you to determine whether to enter the loop based on the key or the remainder, and then insert the ' ('; This method of using the map is very ingenious, before the first number of the loop body. Both the remainder is marked and the position is marked.

2. Consider positive and negative numbers, and overflow

Consider the positive negative number of the result, we first judge the symbol, and then all turn to positive arithmetic.

Consider overflow, if the input is Int.min_value, the absolute value will overflow, so we need to adjust the calculated numerator denominator and the remainder of the type is long or long long.

<span style= "FONT-SIZE:14PX;" >//(2) Get absolute value        //int n = ABS (numerator);        int d = ABS (denominator);        A long long int n = numerator, d = denominator;          N=abs (n);        D=abs (d);                  (3) Calculate integer partial        ret + = to_string (n/d);        Long long int r= n% d;    Remainder R  </span>

The overflow result will become a negative division

30/35 Test cases passed. Status:wrong Answer
Submitted: minutes ago
Input: -1,-2147483648
Output: "0.000000000-4-6-5-6-6-1-2-8-7-30-7-7-3-9-2-5-7-8-1-2-5"
Expected: "0.0000000004656612873077392578125"

3. Handle special cases first, numerator or denominator is 0

<span style= "FONT-SIZE:14PX;" >//Calculate special case, numerator/denominator is 0        if (numerator = = 0) return "0";        if (denominator = = 0) return "";</span>
4. Note The steps we take to calculate division:

(1) The first judgment sign (2) calculates the integer part, whether the surplus number, has, adds the decimal point '. ', continues to calculate; none, returns the result (3) the remainder of 0, and the denominator for division, counted in the results (R *=, ret + = to_string (r/d)) (4) If there are more, the remainder The calculated molecule (R%= D) ends the calculation until the loop is present or there is no remainder.

5. Insert function for string

string& Insert (size_t pos, size_t N, char c);
complexity: O (1) spatial complexity O (1) are constants. Can be expressed as fractions, the description must be a rational number.

AC Code:

<span style= "FONT-SIZE:14PX;" >class Solution {public:string fractiontodecimal (int numerator, int denominator) {//Calculate special case, numerator/denominator is 0 I        F (numerator = = 0) return "0";                if (denominator = = 0) return "";                string ret;                (1) Judging the sign bit if (Numerator < 0 ^ Denominator < 0) ret + = '-';        (2) Obtain the absolute value//int n = ABS (numerator);        int d = ABS (denominator);          A long long int n = numerator, d = denominator;        N=abs (n);                  D=abs (d);        (3) Calculate integer partial ret + = to_string (n/d);    Long long int r= n% d;                Remainder R if (r = = 0) return ret;                RET + = '. ';  (4) Calculate the part of Unordered_map<int, int> Pmap; Record position information remainder position while (R) {//If the remainder appears, the fractional division begins to loop stop the calculation, inserting ' (', at the last insert ') ' if (', ' at the end of the first occurrence ') ' if (pmap.                Count (r) = = 1) {Ret.insert (Pmap[r], 1, ' (');                RET + = ') '; return ret;           }//Record the remainder and position at this time pmap[r] = Ret.size ();            If no loops are present, the division is computed according to the method of handwritten division: 0, Divide, and then the remainder, as the next calculated molecule R *= 10;            RET + = to_string (r/d);        R%= D;    } return ret; }};</span>





[C + +] leetcode:82 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.