Title Description:
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) ".
Problem Solving Ideas:
1. To find out the sequence of the repeating decimal, we need to find the same remainder, then the 2 decimal numbers calculated by the same remainder are repeating decimal;
2. Because of the need to insert parentheses between the Loop series, the hash table is used to record the position of the corresponding result in the case of the remainder.
3. The data of this topic is larger, the use of int type is not enough, need to use int64_t type.
Problem Solving Code:
classSolution { Public: stringFractiontodecimal (int64_t numerator, int64_t denominator) {stringresult =""; if(Numerator * Denominator <0) {result+='-'; } int64_t num= ABS (numerator), den =ABS (denominator); Result+ = to_string (num/den); if(num% den = =0) { returnresult; } Else{result+='.'; } int64_t rem= num%den; Map<int,int>Rem_map; while(REM! =0) { if(Rem_map[rem] >0) {Result.insert (Rem_map[rem],1,'('); Result+=')'; Break; } Rem_map[rem]=result.size (); REM*=Ten; Result+ = to_string (REM/den); REM%=den; } returnresult; }};
[Leetcode] Fraction to recurring Decimal