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) ".
Two questions:
1. How to find the Cycle hour part, the solution is hash table, store the remainder that has already appeared, when he appears again the description begins to loop. This is the same as the happy number solution, where Hash table determines if a loop appears.
The maximum and minimum values of 2.INT, such as int_min=-2147483648, exceed int_max=2147483647 after the absolute value, and the workaround is to use a long long type.
1 classSolution {2 Public:3 stringFractiontodecimal (intNumerator,intdenominator) {4 stringresult;5 Long Longnum=numerator,den=denominator;6 if(numerator==0)7 {8 return "0";9 }Ten if((numerator<0) ^ (denominator<0)) One { Aresult+='-'; - } - if(numerator<0) the { -num=-1*num; - } - if(denominator<0) + { -den=-1*den; + } A Long Longint_part=num/den; atresult+=to_string (int_part); - if(num%den==0) - { - returnresult; - } -result+='.'; in Long Longleft=num%den; -unordered_map<Long Long,int>showed; to while(left) + { - if(Showed.find (left)! =showed.end ()) the { * intposition=Showed[left]; $ stringPART1=RESULT.SUBSTR (0, position);Panax Notoginseng stringPart2=Result.substr (Position,result.length ()); -result = part1+'('+part2+')'; the returnresult; + } Ashowed[left]=result.length (); theleft*=Ten; + intdig=left/den; -Result+=to_string ((Long Long) dig); $left = left%den; $ } - returnresult; - } the};
[Leetcode] Fraction to recurring Decimal