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) "
Topic Link https://leetcode.com/problems/fraction-to-recurring-decimal/
The meaning of the topic is actually very simple, give a divisor and dividend, return the quotient, only if have the loop part, enclose in parentheses.
The topic is simple, always do division until it encounters the remainder of the repetition (each time except, the dividend expands 10 times times, the equivalent of a decimal point backward), with a hashmap to record the appearance of the remainder.
But the test case is really a fortress. The test case will appear (int_min)/(-1) because the absolute value of int_min is 1 larger than the Int_max, so even if the input is INT, the intermediate result is likely to go out of bounds. So you need to use a long long.
There is a trick to using Ostringstream to add and subtract directly from string when constructing the return value, which is much more efficient.
//fraction to recurring DecimalstringFractiontodecimal (intNumerator1,intDenominator1) { Long LongNumerator = (Long Long) (Numerator1); Long LongDenominator = (Long Long) (Denominator1); Ostringstream OS; if(Numerator * Denominator <0) OS<<"-"; Numerator= numerator >0? Numerator: (-numerator); Denominator= Denominator >0? Denominator: (-denominator); Long LongZhengshu = numerator/denominator; Long Longremains = Numerator-zhengshu *denominator; OS<<Zhengshu; if(remains = =0) returnOs.str (); intShang; Vector<int>ans; intCounter =0; intFlag =false; Map<Long Long,int>POS; Map<Long Long,int>:: Iterator it; intposition; while(Remains! =0) {remains*=Ten; It=Pos.find (remains); if(It! =Pos.end ()) {Position= it->second; Flag=true; Break; } Shang= remains/denominator; Ans.push_back (Shang); Pos.insert (Make_pair (Remains, counter++)); Remains= (remains)-(Shang *denominator); } OS<<"."; for(inti =0; I < ans.size (); i++) { if(i = = Position &&flag) OS<<"("; OS<<Ans[i]; } if(flag) OS<<")"; returnos.str ();}
Leetcode-fraction to recurring Decimal