标签:
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,
0.16 6 ) 1.00 0 1 0 <-- Remainder=1, mark 1 as seen at position=0. - 6 40 <-- Remainder=4, mark 4 as seen at position=1. - 36 4 <-- Remainder=4 was seen before at position=1, so the fractional part which is 16 starts repeating at position=1 => 1(6).
1 class Solution { 2 public: 3 string fractionToDecimal(int numerator, int denominator) { 4 5 6 string ans=""; 7 if(numerator==0) return "0"; 8 9 long long int n=numerator; 10 long long int d=denominator; 11 n=abs(n); 12 d=abs(d); 13 14 if(numerator<0^denominator<0) ans.push_back(‘-‘); 15 16 map<long long int,int> hash; 17 18 ans+=to_string(n/d); 19 long long int rem=n%d; 20 if(rem!=0) ans.push_back(‘.‘); 21 22 while(rem!=0) 23 { 24 if(hash.find(rem)!=hash.end()) 25 { 26 ans.insert(hash[rem],"("); 27 ans.push_back(‘)‘); 28 break; 29 } 30 31 hash[rem]=ans.length(); 32 33 ans+=to_string(rem*10/d); 34 rem=(rem*10)%d; 35 } 36 37 return ans; 38 } 39 };
【leetcode】Fraction to Recurring Decimal
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4232228.html