Given integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part was 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.
This problem is still more interesting, and began to worry about if the result is unlimited repeating decimal how to do, after Baidu found that the original can be written scores are rational number, and the rational number is either limited, or infinite circulation of decimals, infinite non-cyclic called irrational number, such as PI or natural number E, primary mathematics did not learn, Khan! Because there are positive and negative conditions, the processing is processed in positive numbers, the symbol at the end of the judgment, then we need to divide the divisor and dividend absolute value, then the problem is: because the integer number int value range is -2147483648~2147483647, The absolute value of 2147483648 will go out of range, so we need to convert to long long and then absolute. So how to find the loop, it must be again to get a number to see if there is no such number before. To save search time, we use a hash table to store numbers on each decimal place. There is also a trick, because we want to figure out each bit, the method is to take the remainder by 10, divided by the divisor, the resulting quotient is the next digit of the decimal number. Wait until the newly calculated number has occurred before, and at the end of the loop, add the opening parenthesis and the closing parenthesis. The code is as follows:
classSolution { Public: stringFractiontodecimal (intNumerator,intdenominator) { intS1 = Numerator >=0?1: -1; intS2 = Denominator >=0?1: -1; Long Longnum = ABS ((Long Long) numerator); Long LongDen = ABS ((Long Long) denominator); Long Long out= num/den; Long Longrem = num%den; Unordered_map<Long Long,int>m; stringres = to_string ( out); if(S1 * s2 = =-1&& ( out>0|| rem >0)) res ="-"+Res; if(REM = =0)returnRes; Res+="."; strings =""; intpos =0; while(REM! =0) { if(M.find (REM)! =M.end ()) {S.insert (M[rem],"("); S+=")"; returnRes +s; } M[rem]=POS; S+ = To_string ((REM *Ten) /den); REM= (REM *Ten) %den; ++POS; } returnRes +s; }};
[Leetcode] Fraction to recurring Decimal score turn repeating decimal