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) ".
0.16 6) 1.00 1 0 <--remainder=1, Mark 1 as seen at position=0. - <--remainder=4, Mark 4 as seen at Position=1. - 4 <--remainder=4 was seen before at Position=1, so the fractional part which is starts REPEA Ting at position=1 = 1 (6).
If the remainder has been found, then the beginning of the cycle, the use of a hash table to record the remainder of the position can be noted that the Int_min converted to a positive overflow, it is necessary to first convert the number first to a long long int note the remainder also to a long long int, because-1, 2147483648 in this case, the remainder will overflow during the calculation multiplied by 10
1 classSolution {2 Public:3 stringFractiontodecimal (intNumerator,intdenominator) {4 5 6 stringans="";7 if(numerator==0)return "0";8 9 Long Long intn=numerator;Ten Long Long intD=denominator; Onen=ABS (n); AD=ABS (d); - - if(numerator<0^denominator<0) Ans.push_back ('-'); the -map<Long Long int,int>Hash; - -Ans+=to_string (n/d); + Long Long intrem=n%D; - if(rem!=0) Ans.push_back ('.'); + A while(rem!=0) at { - if(Hash.find (REM)! =hash.end ()) - { -Ans.insert (Hash[rem],"("); -Ans.push_back (')'); - Break; in } - tohash[rem]=ans.length (); + -Ans+=to_string (rem*Ten/d); theRem= (rem*Ten)%D; * } $ Panax Notoginseng returnans; - } the};
"Leetcode" fraction to recurring Decimal