166. Fraction to Recurring Decimal (Math)

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

 

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        //deal with overflow (eg: -2147483648/-1, -1/-2147483648)
        long l_numerator = (long) numerator;
        long l_denominator = (long) denominator;

        //deal with negative
        string ret = "";
        int p = 0; //pointer to the return string
        if((l_numerator < 0 && l_denominator > 0) || (l_numerator > 0 && l_denominator < 0)) {
            ret += "-";
            p++;
        }
        l_numerator = abs(l_numerator);
        l_denominator = abs(l_denominator);
        
        long quotient = l_numerator/l_denominator; 
        long residue = l_numerator%l_denominator;
        unordered_map<int,int> res_pos_map;
        stringstream ss;
        string sTmp;
        
        ss << quotient;
        ss >> sTmp;
        ret += sTmp;
        p+=sTmp.size();
        
        if(residue!=0) {
            ret += ".";
            p++;
            res_pos_map[residue]=p;
        }
        
        while(residue!=0){
            l_numerator = residue * 10;
            quotient = l_numerator/l_denominator;
            residue = l_numerator%l_denominator;
            ss.clear();
            ss << quotient;
            ss >> sTmp;
            ret += sTmp;
            p++;
            if(res_pos_map.find(residue)==res_pos_map.end()){
                res_pos_map[residue]=p;
            }
            else{
                ss.clear();
                ss << quotient;
                ss >> sTmp;
                ss.clear();
                ss << residue*10/l_denominator;
                ss >> sTmp;
                ret = ret.substr(0,res_pos_map[residue]) + "(" + ret.substr(res_pos_map[residue]) + ")";
                return ret;
            }
        }  
        return ret;
    
    }
};

 

posted on 2017-03-23 01:57  joannae  阅读(109)  评论(0编辑  收藏  举报

导航