[Leetcode]#166 Fraction to Recurring Decimal

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is 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)".
//#166 Fraction to Recurring Decimal
//0ms 100%
class Solution {
public:

    string intToString(long int n)
    {
        string s;
        if(n < 0)
        {
            s.push_back('-');
        }
        else if(n == 0) 
        {
            s.push_back('0');
        }
        while(n != 0)
        {
            s.insert(s.begin(), char((n % 10) + '0'));
            n = n / 10;
        }
        return s;
    }

    string fractionToDecimal(int numerator, int denominator) 
    {
        long int Numerator(numerator), Denominator(denominator);
        string result;
        if(Denominator == 0) return result;
        if((Numerator >= 0 && Denominator <= 0) || (Numerator <= 0 && Denominator >= 0))
        {
            if(Numerator != 0)
            result.push_back('-');
        }
        if(Numerator < 0)
        {
            Numerator = - Numerator;
        }
        if(Denominator < 0)
        {
            Denominator = - Denominator;
        }
        //Numerator = abs(Numerator);
        //Denominator = abs(Denominator);
        long int quotient(0);
        long int remainder(0);

        quotient = Numerator / Denominator;
        remainder = Numerator % Denominator;
        if(quotient > 0)
        {
            result.append(intToString(quotient));
        }
        else //if(quotient == 0)
        {
            if(result.empty() || result[result.size()-1] == '-')
            {
                result.push_back('0');
            }
        }

        if(remainder != 0)
        {
            result.push_back('.');
        }

        map<pair<int, int>, int> recur_map;

        while(remainder != 0)
        {
            /*
            if(remainder >= 214748365)
            {
                cout << "remainder * 10 will overflow, current remainder: " << remainder << endl;
            }
            */
            quotient = (remainder * 10) / Denominator; 
            remainder = (remainder * 10) % Denominator;

            int p(result.size());
            if(recur_map.insert(pair<pair<int, int>, int>(pair<int, int>(quotient, remainder), p)).second == false)
            //recur happens
            {
                //cout << "recur...\n";
                result.push_back(')');
                result.insert(result.begin() + recur_map[pair<int, int>(quotient, remainder)], '(');
                break;
            }
            else
            {
                result.push_back(char(quotient + '0'));
            }
        }

        return result;
    }

};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章