166. Fraction to Recurring Decimal
阿新 • • 發佈:2017-10-06
orm cnblogs 當前 abs pub 位置 ret 設立 bre
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