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) ".
Analysis:
We need to use long type.
Solution:
Store every digit in float part, and assemble the string at last.
1 Public classSolution {2 PublicString Fractiontodecimal (intNumerator,intdenominator) {3 if(denominator==0)return"";4 if(numerator==0)return"0";5 BooleanNeg =false;6 if(numerator>0){7Numerator =-numerator;8NEG =!neg;9 }Ten One if(denominator>0){ ADenominator =-denominator; -NEG =!neg; - } the - - LongIntpart = (Long) numerator/(Long) denominator; - Longleft = numerator%denominator; + -List<integer> digitlist =NewArraylist<integer>(); +List<long> leftlist =NewArraylist<long>(); A intIterstart =-1; at while(left!=0){ - intDigit = (int) (left*10/denominator); - digitlist.add (digit); - Leftlist.add (left); - LongNewleft = (left*10)%denominator; - if(Leftlist.contains (newleft)) { inIterstart =Leftlist.indexof (newleft); - Break; to } +left =Newleft; - } the * //Assemble the string. $StringBuilder Builder =NewStringBuilder ();Panax Notoginseng if(neg) builder.append ('-')); - builder.append (intpart); the + if(Digitlist.size () ==0)returnbuilder.tostring (); A Else { theBuilder.append ('. ')); + if(Iterstart==-1) - for(intI=0;i<digitlist.size (); i++) $ Builder.append (Digitlist.get (i)); $ Else { - //append non-iter part. - for(inti=0;i<iterstart;i++) the Builder.append (Digitlist.get (i)); -Builder.append (' (');Wuyi //append iter part. the for(intI=iterstart;i<digitlist.size (); i++) - Builder.append (Digitlist.get (i)); WuBuilder.append (') '); - } About returnbuilder.tostring (); $ } - - } -}
Solution 2:
Store the postion of the corresponding left of every digit, assemble the result string in place.
1 Public classSolution {2 PublicString Fractiontodecimal (LongNumerator,Longdenominator) {3 if(denominator==0)return"";4 if(numerator==0)return"0";5String res = "";6 if(numerator<0 ^ denominator<0)7res = "-"; 8 9Numerator =Math.Abs (numerator);TenDenominator =Math.Abs (denominator); One A LongIntpart = numerator/denominator; - Longleft = numerator%denominator; -res =Res.concat (long.tostring (Intpart)); theMap<long,integer> Posmap =NewHashmap<long,integer>(); - if(left!=0) res = Res.concat (".")); - while(left!=0){ - Longdigit = left*10/denominator; + Posmap.put (Left,res.length ()); -res =Res.concat (long.tostring (digit)); +left = left*10%denominator; A if(Posmap.containskey (left)) { at intpos =Posmap.get (left); -res = res.substring (0,pos) + "(" +res.substring (Pos,res.length ()) + ")"; -left = 0; - } - } - in returnRes; - to } +}
Leetcode-fraction to recurring Decimal