The fractions into decimals

leet code 166. Fraction to Recurring Decimal

Topic: https://leetcode.com/problems/fraction-to-recurring-decimal/

Problem solution: https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/51160/C%2B%2B-unordered_map

Content Title is: given two numbers n and d, n as molecules, d the denominator gives the corresponding decimal string score. If fractional cycle, using () enclose the part of the cycle.

example:

Input: numerator = 2, denominator = 3
Output: "0.(6)"

Boundary condition problem. Note boundary include: notation, decimal point, the decimal cycle. Remember this title on the line, where there is no need for algorithms.

Symbol XOR may be used. I.e., (n> 0 ^ d> 0), with the number 0, 1 different number.

The remainder can be judged according to the decimal point. After the remainder of the first division is 0, no decimal.

Fractional cycle will need to determine whether the remainder has appeared before, if there have been, to emerge from the last part is the part before the loop.

Total code is as follows:

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if (!numerator) return "0";
        string res;
        // first, decide the sign
        if (numerator > 0 ^ denominator > 0) res += "-";
        // then, decide the integral part
        // attention, negative number can have a large range than positive number
        long n = labs(numerator), d = labs(denominator) , r = n % d;
        res += to_string(n / d);
        // decide the point
        if (!r) return res;
        res += ".";
        // decide the fractional part
        // use a map to deal with repeating part
        unordered_map<long, int> rs;
        while(r){
            // if the rem shows again, then repeat from last time to this time
            if (rs.find(r) != rs.end()){
                res.insert(rs[r], "(");
                res += ")";
                break;
            }
            // save where the r appears
            rs[r] = res.size();
            r *= 10;
            // get next quotient
            res += to_string(r / d);
            r %= d;
        }
        return res;
    }
};

 

Guess you like

Origin www.cnblogs.com/vimery/p/11575584.html