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.
Idea: Take 2/7 as an example:
Class solution {public: String to_string (long x) {STD: String number; STD: stringstream strstream; strstream <X; strstream> Number; return number ;} string fractiontodecimal (INT num, int den) {// although declared as int, if (num = 0) {return "0 ";} string Sign = ""; // The result symbol if (Num> 31) ^ (Den> 31 ))! = 0) {// Sign = "-";} long Numerator = ABS (long) num); // convert it to long, use ABS long Denominator = ABS (long) Den); If (numerator % Denominator = 0) {// return sign + to_string (numerator/denominator);} Long n = numerator/denominator; // The integer part Numerator = numerator % denominator; // molecular map <int, int> m; long I = 0; string S = ""; bool flag = false; while (M. find (numerator) = m. end () {M [numerator] = I; numerator * = 10; I ++; If (Numerator = 0) {// flag = true; break ;} if (numerator <denominator) {// fill in 0 S + = "0";} else {int L = numerator/denominator; S + = to_string (L ); numerator % = Denominator;} If (FLAG) {return sign + to_string (n) + ". "+ S;} int Index = m. find (numerator)-> second; return sign + to_string (n) + (". "+ S. substr (0, index) + "(" + S. substr (index, I-index) + ")";}};
Fraction to recurring decimal