美文网首页
166. Fraction to Recurring Decim

166. Fraction to Recurring Decim

作者: yunmengze | 来源:发表于2018-09-30 00:13 被阅读0次

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.

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:

Input: numerator = 2, denominator = 1
Output: "2"
Example 3:

Input: numerator = 2, denominator = 3
Output: "0.(6)"

这道题可以按照正常的除法计算方法来。使用一个哈希表来保存每次得到的余数,如果遇到相同的余数,说明小数部分开始重复。

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        string res;
        unordered_map<int,int> data;
        if(numerator == 0)
            return "0";
        long numerator_1 = numerator;
        long denominator_1 = denominator;
        //获取结果的符号
        if((numerator ^ denominator) < 0)
            res.push_back('-');
        numerator_1 = abs(numerator_1);
        denominator_1 = abs(denominator_1);
        long integer = numerator_1 / denominator_1;
        long remainder = numerator_1 % denominator_1;
        res += to_string(integer);
        if(remainder == 0){
            return res;
        }
        res += '.';
        string digit = "";
        int beginId = 0;
        while(remainder != 0 && data.find(remainder) == data.end()){
            data[remainder] = beginId++;
            remainder *= 10;
            long devideRes = remainder / denominator_1;
            remainder = remainder % denominator_1;
            digit += to_string(devideRes);
        }
        if(remainder == 0){
            res += digit;
            return res;
        }
        else{
            int index = data[remainder];
            digit.insert(index, 1, '(');
            digit.push_back(')');
            res += digit;
            return res;
        }
    }
};

相关文章

网友评论

      本文标题:166. Fraction to Recurring Decim

      本文链接:https://www.haomeiwen.com/subject/ahjioftx.html