There are too many corner cases for this problem when numerator and denominator are Integer.MIN_VALUE, so convert them to long type to avoid taking care of corner cases.
Basically, it will keep calculating reminder until either it equals to 0 or it appears before(repeating decimal). Use hashmap to store the position of the reminder, so when it reappears, we can insert '(' to the right position.
public String fractionToDecimal(int numerator, int denominator) {
boolean neg=(numerator>0 && denominator<0) || (numerator<0 && denominator>0);
long numLong=Math.abs((long)numerator);
long denomLong=Math.abs((long)denominator);
long res=numLong/denomLong;
numLong=numLong%denomLong;
StringBuilder sb=new StringBuilder();
if(neg) sb.append("-");
sb.append(Math.abs(res));
if(numLong==0) return sb.toString();
sb.append('.');
HashMap<Long,Integer> used=new HashMap<Long,Integer>();
while(numLong!=0 && !used.containsKey(numLong)){
used.put(numLong,sb.length());
sb.append(numLong*10/denomLong);
numLong=numLong*10%denomLong;
}
if(numLong!=0)
{
sb.append(")");
sb.insert(used.get(numLong),"(");
}
return sb.toString();
}
No comments:
Post a Comment