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)".
Analyse: Use hash to store the fractional and its corresponding position at result. If the fractional has occurred, the result is recurring; If the fractional is 0, return current result.
Runtime: 0ms.
1 class Solution { 2 public: 3 string fractionToDecimal(int numerator, int denominator) { 4 if(!numerator) return "0"; 5 6 string result; 7 unordered_map<int, int> um; 8 if(numerator < 0 ^ denominator < 0) result += '-'; 9 long long int nu = numerator, de = denominator; 10 nu = abs(nu); 11 de = abs(de); 12 13 result += to_string(nu / de); 14 long long int fractional = nu % de; 15 if(!fractional) return result; 16 result += "."; 17 18 while(fractional) { 19 // find if the fractional is in um 20 if(um.find(fractional) != um.end()) { 21 result.insert(um[fractional], "("); 22 result += ")"; 23 return result; 24 } 25 26 // push the fractional and its position in result into um 27 um[fractional] = result.length(); 28 29 fractional *= 10; 30 result += to_string(fractional / de); 31 fractional %= de; 32 } 33 return result; 34 } 35 };