Fraction to recurring Decimal
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.
The problem is done by definition.
If it is not divisible, the remainder is continuously 0 divided by the divisor.
Maintains a mapping table Map<long long, int> m, used to record the position of each remainder corresponding to the return value in Ret.
(1) When the repetition of the remainder R, the description found the loop body, according to M[r] Find the position of RET, plus the corresponding ' (' and ') ' to enclose the loop body can be returned.
(2) When the remainder R is 0 o'clock, return to Ret.
Note: There may be int_min/-1 out of bounds, so the first step is now to convert int to long long int
classSolution { Public: stringFractiontodecimal (intNumerator,intdenominator) { returnHelper (numerator, denominator); } stringHelper (Long LongNumerator,Long Longdenominator) { //convert to 64_int in case int_min/-1 overflow//Special Case if(Denominator = =0) return ""; Else if(Numerator = =0) return "0"; stringRET =""; if((numerator<0) ^ (denominator<0)) {//One of them is negative, with bit orRET + ='-'; Numerator=ABS (numerator); Denominator=ABS (denominator); } //integer part if(Numerator/denominator = =0) //integer part is 0RET + ='0'; Else { Long Longquotient = numerator/denominator; RET+=to_string (quotient); if(Numerator%denominator = =0) //divisible returnret; Else //Not divisible, numerator as remainderNumerator-= (quotient*denominator); } //Decimal partRET + ='.'; stringdemical; Map<Long Long,int> m;//<remainder, index> pair Long LongR =numerator; while(r) {if(M.find (r)! =M.end ()) {//remainderRet.insert (M[r],1,'(');//Insert (iterator p, size_t N, char c);RET + =')'; Break; } M[r]=ret.size (); R*=Ten;//Next DigitRET + = to_string (r/denominator); R%=denominator; } returnret; }};
"Leetcode" fraction to recurring Decimal