Fraction to Recurring Decimal

Total Accepted: 23332 Total Submissions: 166240 Difficulty: Medium

 

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) {
        if(numerator==0){
            return "0";
        }
        string res;
        int index = 0;
        if( ((numerator>>31)&1)^((denominator>>31)&1)){//异号
            res.push_back('-');
            index++;
        }
        long long int num = numerator;//long long int 防止溢出
        long long int den = denominator;
        num = fabs(num);
        den = fabs(den);
        
        int start=0;//无限循环小数的左括号的位置
        bool first = true;  //是否需要加小数点的标志
        unordered_map<long long int,int> numers;//用于判断被除数是否出现过
        while(num){
            if(numers[num] != 0){
                start = numers[num]-1;
                break;
            }
            numers[num] = index+1;
            if(num/den != 0){
                string tmp = to_string(num/den);
                res.append(tmp.begin(),tmp.end());
                index += tmp.size();
            }else{
                res.push_back('0');
                index++;
            }
            long long int remaind = num%den;
            if(remaind!=0 && first){
                res.push_back('.');
                index++;
                first = false;
            }
            num = remaind*10;
        }
        if(start!=0){
            res.insert(res.begin()+start,'(');
            res.push_back(')');
        }
        return res;
    }
};

 

posted @ 2015-12-16 19:14  zengzy  阅读(201)  评论(0编辑  收藏  举报
levels of contents