166. Fraction to Recurring Decimal

Posted 为了更优秀的你,加油!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)".

解题思路:一个循环小数,必然是由于余数循环开始的。整数部分肯定是有限的,循环是从小数部分或者说余数部分开始的,于是设立个map,每次把余数映射到当前res的最末尾,如果开始循环之后,在此位置放左括号。

class Solution {
public:
    string fractionToDecimal(int numerator, int denominator) {
        if(numerator==0)return "0";
        string res;
        if((numerator>0)^(denominator>0))res+=-;
        long long int n=abs((long)numerator),d=abs((long)denominator),r=n%d;
        res+=to_string(n/d);
        if(!r)return res;
        res+=.;
        unordered_map<long long, long long>hash;
        for(;r;r=r%d){
            if(hash[r]){
                res.insert(hash[r],1,();
                res+=);
                break;
            }
            hash[r]=res.size();
            r*=10;
            res+=to_string(r/d);
        }
        return res;
    }
};

 

以上是关于166. Fraction to Recurring Decimal的主要内容,如果未能解决你的问题,请参考以下文章

166. Fraction to Recurring Decimal

166. Fraction to Recurring Decimal

166. Fraction to Recurring Decimal

166. Fraction to Recurring Decimal

166. Fraction to Recurring Decimal

Leetcode 166 Fraction to Recurring Decimal