标签:小数 += nat integer 思路 form repr amp solution
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,
解题思路:一个循环小数,必然是由于余数循环开始的。整数部分肯定是有限的,循环是从小数部分或者说余数部分开始的,于是设立个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
标签:小数 += nat integer 思路 form repr amp solution
原文地址:http://www.cnblogs.com/tsunami-lj/p/7631625.html