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)".
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
注意溢出:特例-2147483648, 1 | -1, -2147483648 |
- string to_string(long long n) {
- stringstream ss;
- ss<<n;
- string result;
- ss>>result;
- return result;
- }
- string fractionToDecimal(int numerator, int denominator) {
- if(numerator == 0) return "0";
- string result;
- if(numerator<0 ^ denominator<0) result += '-';
- long long n = numerator, d = denominator;
- n = abs(n);
- d = abs(d);
- result += to_string(n/d);
- long long r = n%d;
- if(r == 0) return result;
- else result += '.';
- unordered_map<int,int> exist;
- while(r!=0) {
- if(exist.find(r) != exist.end()) {
- result.insert(exist[r],1,'(');
- result += ')';
- break;
- }
- exist[r] = result.size();
- r *= 10;
- result += to_string(r/d);
- r = r % d;
- }
- return result;
- }