Description:
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) ".
Solution:
Long Division: longer Division
Trick:determining whether the nums has different sign (+ or –) can use follow codes:
if ((n<0) ^ (d<0)) // different number or if ((n>0) ^ (d>0)) // different number
Above code Avoiding product ' s value overflow.
Code:
classSolution { Public: stringFractiontodecimal (intNumerator,intdenominator) { if(!numerator)return "0"; Long Longn = numerator, d =denominator; stringRET =""; if((n<0) ^ (d<0)) ret + ='-'; if(N <0) n =-N; if(D <0) d =-D; RET+ = To_string (n/d); if(n% d = =0){ returnret; }ret+='.'; Map<Long Long,int>Hash; for(Long Longr = n% d; R R%=d) { if(Hash.find (r)! =Hash.end ()) {Ret.insert (hash[r],"("); RET+=")"; returnret; } Hash[r]=ret.size (); R*=Ten; RET+ = To_string (R/d); } }};
"Leetcode 166" fraction to recurring Decimal