Fraction to Recurring Decimal

思路:1、对分子为0的可以提前返回

         2、结果为正负的判断

        3、数组越界(最小负数除以-1)

        4、对于遇到小数的开始要加上“.”,有小数后可以扩大被除数,对于是否有重复的地方要判断其被除数是否重复了!!!

对于abs()函数切记,先把数转换为长整型,然后再用abs(),否则最小负数是转换不了正数的!!!

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        string res;
        if(numerator==0) return "0";
        if((numerator<0)^(denominator<0))
        res+="-";
        long long n=numerator;
        long long d=denominator;
        n=abs(n);
        d=abs(d);
        unordered_map<int,int> rep;
        bool isFract=false;
        while(true)
        {
            if(n<d)
            {
                if(isFract==false)
                {
                    if(res==""||res=="-")
                    res+="0.";
                    else 
                    res+=".";
                    isFract=true;
                }
                  n*=10;
            }
            int r=n-n/d*d;
            if(r==0)
            {
               res+=to_string(n/d);
               return res;
            }
            else
            {
                if(isFract==true)
                {
                    if(rep.find(n)==rep.end())
                     {
                         res+=to_string(n/d);
                         rep[n]=res.size()-1;
                     }
                     else
                     {
                         int pos=rep[n];
                         res=res.substr(0,pos)+"("+res.substr(pos)+")";
                         return res;
                     }
                }
                else
                 res+=to_string(n/d);
                 n=r;
            }
            
        }
    }
};
原文地址:https://www.cnblogs.com/daocaorenblog/p/5332426.html