Wednesday, January 28, 2015

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)".
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if (denominator == 0)
            return "";
        if (numerator == 0)
            return "0";
        bool negative = false;
        long a = numerator;
        long b = denominator;
        if (a<0) 
        {   
            negative = !negative;
            a = abs(a);
        }
        if (b<0) 
        {
            negative = !negative;
            b = abs(b);
        }
        
        string res = help(a,b);
        if (negative)
            res.insert(res.begin(),'-');
        return res;
    }
    string help(long numerator,long denominator)
    {
        string res;
        long integer = numerator/denominator;
        res+= int2str(integer);
        numerator %= denominator;
        if (numerator!=0)
            res+= '.';
        int pos=res.size();
        bool loop = false;
        unordered_map<int,int> mp;
        while(numerator!=0)
        {
            if (mp.find(numerator)==mp.end())
                mp[numerator]=pos;
            else
            {
                pos = mp[numerator];
                loop = true;
                break;
            }
            numerator *=10;
            res+= numerator/denominator +'0';
            numerator %= denominator;
            pos++;
        }
        if (loop)
        {
            res.insert(res.begin()+pos,'(');
            res+= ')';
        }
        return res;
    }
    string int2str(long a)
    {
        if (a==0)
            return "0";
        string res;
        while(a>0)
        {
            char c = a%10 + '0';
            res.insert(res.begin(),c);
            a /=10;
        }
        return res;
    }
};

No comments:

Post a Comment