166. Fraction to Recurring Decimal

来源:互联网 发布:淘宝店铺更改所在地 编辑:程序博客网 时间:2024/05/19 09:17

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)    {        return fractionToDecimalCore(numerator,denominator);    }    string fractionToDecimalCore(int64_t numerator,int64_t denominator) {        if(numerator == 0)            return "0";        string ret;                //determine the sign using xor        if(numerator<0 ^ denominator<0)            ret+="-";        numerator = abs(numerator);        denominator = abs(denominator);                //append the integral part        ret+=to_string(numerator/denominator);                //in case,there is no fractional part        if(numerator%denominator ==0)            return ret;                //add the decimal point        ret+=".";                unordered_map<int,int> map;        for(int64_t remainder = numerator%denominator;remainder;remainder%=denominator)        {            //we find a repeating remainder            if(map.count(remainder) > 0)            {                ret.insert(map[remainder],1,'(');                ret+=')';                break;            }                        map[remainder] = ret.size();                        remainder*=10;            ret+=to_string(remainder / denominator);        }                return ret;                            }};


0 0
原创粉丝点击