[LeetCode] Fraction to Recurring Decimal
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 )".
Question meaning:
Converts a score to a circular decimal number. The general idea is: Use two maps to record the quotient, its location, its remainder, and its location. If there is a repeated remainder, it indicates that the quotient starts to loop at the corresponding position of the remainder. This question has many traps. The Code is as follows:
Class Solution {public: string fractionToDecimal (int numerator, int denominator) {string result = ""; long numberatorL = (long) numerator; long denominatorL = (long) denominator; if (numberatorL * denominatorL <0) {// note the negative result + = "-"; numberatorL =-numberatorL;} long quotient = numberatorL/denominatorL; // vendor result + = intToStr (quotient); long remainder = numberatorL % denom InatorL; // The remainder if (remainder! = 0) {result + = '.'; int position =-1; int repeatStartPosition =-1; // loop start position map
PositionToQuotient; // the location to the quotient, starting from a certain position as the cyclic decimal map
RemainderToPosition; // the remainder to the position remainderToPosition. insert (map
: Value_type (remainder, position); position ++; while (remainder! = 0) {remainder * = 10; quotient = remainder/denominatorL; remainder = remainder % denominatorL; positionToQuotient. insert (map
: Value_type (position, quotient); map
: Iterator it = remainderToPosition. find (remainder); if (it! = RemainderToPosition. end () {// if the remainder already exists repeatStartPosition = it-> second + 1; break;} remainderToPosition. insert (map
: Value_type (remainder, position); position ++;} for (map
: Iterator it = positionToQuotient. begin (); it! = PositionToQuotient. end (); it ++) {if (it-> first = repeatStartPosition) {result + = "(" ;}result + = intToStr (it-> second );} if (repeatStartPosition> = 0) {result + = ")" ;}} return result;} private: string intToStr (long number) {string result = ""; do {result = (char) (number % 10 + '0') + result; number/= 10;} while (number! = 0); return result ;}};